use knockout js observable value as variable - c#

I have the following:
<span data-bind="text: total"></span>
from knockout js, how can I pass this value to code behind ?

Carsten was accurate with the ajax call. You'll have an event, possibly from a button click, with a function that does something like,
//html
//... form that adds to total
<span data-bind="text: total"></span>
<button data-bind="click: mySubmit">Submit Total</button>
//js controller
self.total = 0;
self.mySubmit = function(){
$.ajax({
type: "POST",
url: myBackendControllerUrl,
data: self.total,
success: function(){console.log("success!");},
dataType: JSON
});
}
Knockout is a clientside framework. To get your data from the client, to the server, you'll need something like the above. You'll need to create a controller on your server side that can receive this. I hope this helps get you started.

Related

Refresh ReportViewer with new SQL data

I have a website that uses a ReportViewer to display a SSRS serverside report. I also have controls/textboxes that are used to update the data behind using jQuery/AJAX. I want to try to avoid any page reloads.
I am now trying to refresh the ReportViewer after I have updated my data, without having the page reloaded. Unfortunately, I don't understand if there is a way to (re)load the new data into the ReportViewer. Using the refreshReport method in the ReportViewer control only rerenders with the old data.
Data gets updated with this code, the ReportViewer / report refreshes, but with the old data.
Can I get the new data from the database into the report without having some kind of page reload?
<script type="text/javascript">
function SaveData() {
var data = { text: $('#textBox').val() }
$.ajax({
type: "POST",
url: "ajax.aspx/SaveData",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
}
});
}
function OnSuccess(response) {
var clientViewer = $find("MainReportViewer");
if (clientViewer) {
clientViewer.refreshReport();
}
}
</script>
<rsweb:ReportViewer ID="MainReportViewer" runat="server" ProcessingMode="Remote" Width="100%" Height="100%" AsyncRendering="False" SizeToReportContent="True" ShowToolBar="False" ShowParameterPrompts="False">
<ServerReport ReportPath="/Rep/Rep" ReportServerUrl="http://localhost/reportserver" />
</rsweb:ReportViewer>
<button id="SaveButton" name="SaveButton" type="button" onclick="SaveData()" class="ui-button ui-widget ui-corner-all ui-button-icon-only"><span class="ui-icon ui-icon-disk"></span> </button>
Follow the below steps to make it work:
Use The Timer like ASP.net Timer and JavaScript Timer
refresh Data From Database every Tick and Use Tick Event
the Elapse Time Out then Your Data Reload withOut Page Refresh
Dude these steps definitely work.
any queries please ask in comments.

call function in 'code behind' with AJAX in ASP.NET WebForms?

I want to get access to a method in code behind when I clicked an span in my view aspx:
DEFAULT.ASPX VIEW CODE:
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<%-- MY SPAN --%>
<span runat="server" onclick="ShowChartSpider(this.id)" id="group_2" style="cursor: pointer" class="pull-right">My Span</span>
<%-- JAVASCRIPT CODE --%>
<script type="text/javascript">
function ShowChartSpider(group_id) {
$.ajax({
type: "POST",
url: "Default.aspx/MethodToCreateChart",
dataType: "json",
data: "{'parameter1':" + JSON.stringify(group_id) + "}",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("all correct");
},
error: function (data) {
alert("no");
}
}
);
}
</script>
</asp:Content>
DEFAULT.ASPX.VB CODE BEHIND:
<WebMethod()>
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Shared Sub MethodToCreateChart(sender As Object, e As EventArgs)
' My code to create the chart .....
End Sub
if I run the page, and inspects the page with the browser to see errors, none appear, but the code does not reach the breakpoint that I put in the method in codebehind.
What I´m doing wrong?
I would appreciate suggestions, thanks.
First check your server allow non HTTPS request.
i had that type of issue and my server didn't allow me to do that.
it so then disable that and test.
Then check the response status.
error: function(xhr, status) {
alert(xhr.status); }
let us know that is the outcome.
--Ruhul
Go to "RouteConfig.vb" under "App_Start" folder.
Change following line
settings.AutoRedirectMode = RedirectMode.Permanent
To
settings.AutoRedirectMode = RedirectMode.Off
i think your method code returning something like this.
Return Default.aspx/MethodToCreateChart
so me your MethodToCreateChart logic.
you can try with below sample method. your internal server error are coming because you are returning somethng from your method.
Public Shared Function MethodToCreateChart(parameter1 As String) As String
Return "Hello " & Environment.NewLine & "The Current Time is: " & _DateTime.Now.ToString()
End Function
I think you should remove 'runat=server' attribute from span tag.
You use aspx file same as ashx files. So have a look at below links:
1. How do you debug ASP.net HTTPHandler
2. Can't debug ASHX handler

JQuery AJAX Post Inside Partial View

In my C# MVC4 application, I have two main views: "Index" and "Index_Perm." The logged-in user's role is what determines which of these views is rendered. "Index" contains a view called "PMain" and Index_Perm" contains a view called "PMain_Lim." "PMain" and "PMain_Lim" contain another partial view called "Analysis." Inside of "Analysis", I have this script:
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#SubmitAverage').click(function () {
var $form = $('#form1');
$.ajax({
type: "POST",
url: "Home/Average",
data: $form.serialize(),
success: function () {
alert("Edit successful");
},
error: function () {
alert('failure');
}
});
});
});
</script>
My issue is that, when "Index" is the main view being accessed this script runs correctly when the Submit button is clicked. When "Index_Perm" is the main view however, when the button is clicked, the AJAX post fails with the error: The resource you are looking for has been removed, had its name changed, or is temporarily unavailable. The directory or file specified does not exist on the Web server. After some investigation in Firebug, I see that it is trying to access: mylocalhost/Home/Index_Perm/Home/Average instead of: mylocalhost/Home/Average which is specified as the url to send the POST in my script.
Here is the applicable portion of code which is identical in "PMain" and "PMain_Lim" which contains the button that is tied to the script:
<div id="Analysis" title="Analysis">
#Html.Action("Analysis", "Home", Model)
</div>
</section>
<section>
<h3>
<button class="btn" id="SubmitAverage" value ="SubmitAverage" name="action:SubmitAverage" type="button">Submit Averages</button>
</h3>
</section>
<section>
<div id="OtherView" title="OtherView" class="OtherChanges">
#Html.Action("OtherView", "Home", (string)ViewBag.SearchKey)
</div>
</section>
Any ideas why its ignoring what I've specified as the URL to use in the JQuery AJAX POST and/or how to correct it?
Use the urlhelper in your ajax post
url: '#Url.Action("Average","Home")',

How to automatically run method when the ASP page is loaded?

I have a page which displays the following content when it is loaded:
<div>
<img src="loading.gif" alt="Loading" /> Generating PDF Document, please wait.
<div>
At the same time, I want to run this method the code behind automatically:
private void GeneratePdf()
{
...
}
Lastly, I want to redirect the user to the File.pdf path once the GeneratePdf() method is completed.
How do I do this?
You need to use the Page_Load event as explained here. Additionally, this is a great explanation of the page life cycle. You should take a look at it. Here is some sample code from the above link:
<script runat="server">//This script runs on the server and dishes up some output for the page.
Sub Page_Load
lbl1.Text="The date and time is " & now()
End Sub
</script>
<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>//This generates the textbox that will be given a value from the above script.
</form>
</body>
</html>
Hope this helps you!
I suggest to use GeneratePDF with ajax, so you can use like
$.ajax({
url: '/pdf/fiele_to_generate_pdf.aspx',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: $.toJSON(jsonObj),
processData: false,
dataType: 'html',
async: false,
success: function(html) {
window.location.href = '/pdf/example.pdf';
}});
so for loading you can use jquery, there is a good plugin named BlockUI you can use it before your ajax call.
You can use the asp:Timer control to indicate when your code-behind should be called
<asp:Timer runat="server" ID="timer1" Interval="3000" OnTick="timer1_Tick"></asp:Timer>
Then implement the Timer's Tick event. This will be called after 3 seconds (3000ms) as specified in the markup
protected void timer1_Tick(object sender, EventArgs e)
{
GeneratePdf();
Response.Redirect("~/somepath/generatedPDF.pdf");
}

How to run Facebook Social Plugin Javascript From CodeBehind C#?

I have a website where i want my visitors to invite their friends. I'm using the Requests Dialog for this. But now i want to add a dynamic text message to this invite.
The dynamic text is generated in an c# code behind file. But the Request Dialog is triggered with javascript.
Here is the Request Dialog part on my aspx page:
<div id="fb-root"></div>
<script src="http://connect.facebook.net/nl_NL/all.js">
</script>
<script>
FB.init({
appId: '[MY-APP-ID]', cookie: true,
status: true, xfbml: true
});
function inviteFriends() {
FB.ui({ method: 'apprequests', message: '[THE DYNAMIC MESSAGE I WANT TO SEND]', data: 'tracking information for the user' });
}
</script>
Is it possible to call this javascript form codebehind code and pass the message parameter too?
Thanks in advance!
You can use <%= ... %> to expose your code to page (assuming you have message in requestsDialogMessage variable):
FB.ui({
method: 'apprequests',
message: '<%= requestsDialogMessage %>',
data: 'tracking information for the user'
});
Other way may be exposing the message to some JavaScript variable and using it within FB.ui call:
<script>
var exposedData = {
requestsDialogMessage: '<%= requestsDialogMessage %>'
};
</script>
And later in your JS code:
FB.ui({
method: 'apprequests',
message: exposedData.requestsDialogMessage,
data: 'tracking information for the user'
});

Categories

Resources