Asked by:
Call C# function with JQuery

Question
-
User-247642986 posted
Hi,
I am struggling with calling a c# function with JQuery.
Been searching a lot and see a lot but nothing seems to work for me. And why I don' know.
So here is what I have so far.
Page is ASPX page with Sitemater page with scriptmanager
<asp:ScriptManager runat="server" ID="myDAscripts" EnablePageMethods="true" >
On the form i placed a button
<asp:Button CssClass="btn btn-primary" runat="server" ID="btnCreate" Text="Aanmaken" CausesValidation="True" UseSubmitBehavior="False" OnClientClick="SendData(event)" type="button" />
Script for button:
<script type="text/javascript"> function SendData(e) { e.preventDefault(); $.ajax({ type: "POST", url: "CreateCall.aspx/SubmitCall", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { if (response.d) { alert("Succes"); } else { alert("Failed.") } }, error: function (response) { alert("Error: " + response.d); } }); return false; } </script>
The function in c#:
[WebMethod] public static bool SubmitCall() { try { return true; // Config the WCF Service using (RobisService.RobisServiceClient Robis = new RobisService.RobisServiceClient("RobisService", ConfigurationManager.AppSettings["endpointAddress"])) { // Set parameters RobisService.CreateCall CallData = new RobisService.CreateCall(); RobisService.CreateCallResult Result = new RobisService.CreateCallResult(); // Set the call data //CallData.RelationID = LoginData.ClientID; //CallData.SupportID = Convert.ToInt32(lstLocations.SelectedValue); //CallData.ContactID = LoginData.ContactID; //CallData.CommPhonenumber = txtCommPhoneNumber.Text; //CallData.CommEmailAddress = txtCommEmail.Text; //CallData.ProblemDescription = txtDescription.Text; //CallData.ClientReference = txtClientReference.Text; //CallData.UserName = txtUserName.Text; //CallData.UserPhonenumber = txtUserPhonenumber.Text; //CallData.UserEmailAddress = txtUserEmail.Text; //CallData.HandleWithPrio = cbPrio.Checked; // Submit the call Result = Robis.CallCreate(ref CallData); // Check if call has been created if (Result.CallCreated) { //// Set callnumber in popup panel //lblInfo2.Text = Result.Callnumber; //// Show popup panel //popupSucces.Show(); //return true; } else { //// Set error message //lblFailedTitle.Text = Result.ErrorMessage; //lblFailedDetails.Text = Result.ErrorDetails; //// Show error //popupFailed.Show(); //return false; } } } catch (Exception ex) { //// Set error message //lblFailedTitle.Text = "Probleem met verwerken van de gegevens."; //lblFailedDetails.Text = ex.Message; //// Show error //popupFailed.Show(); return false; } }
I followed a lot of examples on the internet but the process is not working.
The result shown is always "Failed"
Placed a breakpoint in my function, but that is not hit.
So I definitely missing something I am still learning so be gentle.
Hope someone can help me with this problem and show where I go wrong.
Greetings,
Ernst Jan.
Monday, September 12, 2016 2:58 PM
All replies
-
User1213248666 posted
Hi,
I think the problem is,not call the function
Try these small changes in your code.
Remove event in SendData(event) and remove event in script as well.
Now you place the breakpoint in the function and check whether it hit the function or not.
<asp:Button CssClass="btn btn-primary" runat="server" ID="btnCreate" Text="Aanmaken" CausesValidation="True" UseSubmitBehavior="False" OnClientClick="SendData()" type="button" />
<script type="text/javascript"> function SendData() { $.ajax({ type: "POST", url: "CreateCall.aspx/SubmitCall", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { if (response.d) { alert("Success"); } else { alert("Failed.") } }, error: function (response) { alert("Error: " + response.d); } }); return false; } </script>
Monday, September 12, 2016 10:48 PM -
User2117486576 posted
The url in the Ajax method is probably not correct. Use this syntax to render the proper URL:
url: '<%= ResolveUrl("~/CreateCall.aspx/SubmitCall") %>',
Make sure to enable page methods in your script manager. See this:
http://stackoverflow.com/questions/6928533/calling-a-webmethod-with-jquery-in-asp-net-webforms
Tuesday, September 13, 2016 12:26 AM -
User-247642986 posted
Hi,
thx for replying and trying to help me with the problem.
The suggestions sadly didn't solve my problem.
Still getting failed as result.
Have been trying different things to try and find out what I am missing or overlooking.
<script type="text/javascript"> function SendData() { alert("Clicked"); $.ajax({ type: 'POST', url: '<%= ResolveUrl("~/CreateCall.aspx/SubmitCall") %>', data: '{}', contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (response) { //if (response.d) //{ // alert("Succes"); //} //else //{ alert(response.d) //} } }); return false; }; </script>
I now get first the message "Clicked" and after that "undefined".
When I change the page in the url I will see "Clicked" but nothing else after that. So I think the page is being resolved. The function name has no effect. Still getting "Undefined" as last message.
Just to make sure. The function is in the code behind the page. Here is the compleet code:
namespace myDA_Portal { public partial class CreateCall : System.Web.UI.Page { public RobisService.LoginResultData LoginData; Boolean bSingle = true; protected void Page_Load(object sender, EventArgs e) { // Set login data LoginData = (RobisService.LoginResultData)Session["LoginData"]; // Check if user has been logged in if (Session["username"] == null) { // Redirect to login page Response.Redirect("LoginPage.aspx"); } // Check that it is not a postback if (!IsPostBack) { // Config the WCF service using (RobisService.RobisServiceClient Robis = new RobisService.RobisServiceClient("RobisService", ConfigurationManager.AppSettings["endpointAddress"])) { // Create the table RobisService.ClientLocations[] Locations = new RobisService.ClientLocations[0]; RobisService.ProcessResult result; // Load the data specific for client result = Robis.getClientLocations(ref Locations, LoginData.ClientID); // Check if there was an error if (!result.Result) { Session["ErrorModule"] = "Openen =aanmaken call formulier"; Session["ErrorMessage"] = result.ErrorInfo; Response.Redirect("ErrorPage.aspx"); } // Set selection list lstLocations.DataSource = Locations; lstLocations.DataTextField = "RelationName"; lstLocations.DataValueField = "RelationID"; lstLocations.DataBind(); // Set default communication data txtCommEmail.Text = LoginData.EmailAddress; txtCommPhoneNumber.Text = LoginData.PhoneNumber; // Set location selection fields LocationGrp.Visible = (Locations.Length != 1); bSingle = (Locations.Length == 1); // If there is a list add extra row if (Locations.Length > 1) { lstLocations.Items.Insert(0, new ListItem("<Selecteer locatie>", "0")); } // Determine which field gets focus if (LoginData.PhoneNumber == String.Empty) { // Set focus to communication phonenumber txtCommPhoneNumber.Focus(); } else if (LoginData.EmailAddress == String.Empty) { // Set focus to communication email address txtCommEmail.Focus(); } else { // Set focus to description txtDescription.Focus(); } } } } protected void btnCloseSucces_Click(object sender, EventArgs e) { // Reload page Response.Redirect(Request.RawUrl); } protected void btnSubmit_Click(object sender, EventArgs e) { } [WebMethod] public static bool SubmitCall() { try { return true; // Config the WCF Service using (RobisService.RobisServiceClient Robis = new RobisService.RobisServiceClient("RobisService", ConfigurationManager.AppSettings["endpointAddress"])) { // Set parameters RobisService.CreateCall CallData = new RobisService.CreateCall(); RobisService.CreateCallResult Result = new RobisService.CreateCallResult(); // Set the call data //CallData.RelationID = LoginData.ClientID; //CallData.SupportID = Convert.ToInt32(lstLocations.SelectedValue); //CallData.ContactID = LoginData.ContactID; //CallData.CommPhonenumber = txtCommPhoneNumber.Text; //CallData.CommEmailAddress = txtCommEmail.Text; //CallData.ProblemDescription = txtDescription.Text; //CallData.ClientReference = txtClientReference.Text; //CallData.UserName = txtUserName.Text; //CallData.UserPhonenumber = txtUserPhonenumber.Text; //CallData.UserEmailAddress = txtUserEmail.Text; //CallData.HandleWithPrio = cbPrio.Checked; // Submit the call Result = Robis.CallCreate(ref CallData); // Check if call has been created if (Result.CallCreated) { //// Set callnumber in popup panel //lblInfo2.Text = Result.Callnumber; //// Show popup panel //popupSucces.Show(); //return true; } else { //// Set error message //lblFailedTitle.Text = Result.ErrorMessage; //lblFailedDetails.Text = Result.ErrorDetails; //// Show error //popupFailed.Show(); //return false; } } } catch (Exception ex) { //// Set error message //lblFailedTitle.Text = "Probleem met verwerken van de gegevens."; //lblFailedDetails.Text = ex.Message; //// Show error //popupFailed.Show(); return false; } } } }
Something that I tried but was not working was the next piece of code
$('#btnCreate').click(function() {alert("Clicked");
$.ajax({
type: 'POST',
url: '<%= ResolveUrl("~/CreateCall.aspx/SubmitCall") %>',
data: '{}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
//if (response.d)
//{
// alert("Succes");
//}
//else
//{
alert(response.d)
//}
}
});
return false;}I did not recief the message "Clicked" so that made me think the code is not executed.
Maybe this is an indication where the problem might be.
Thanks in advance for all your help.
Greetings,
Ernst Jan
Tuesday, September 13, 2016 7:44 AM -
User2117486576 posted
alert(response.d)This will always show "undefined" because SubmitCall() WebMethod does not return an object with a property: d. The WebMethod only returns a string: "true". Modify the $.ajax method to define an error callback. Then set a break point in both the success and error callbacks to see which one is executed. Inspecting the return value or error code will tell you what is happening.
Tuesday, September 13, 2016 1:51 PM -
User-247642986 posted
Hi RichardY,
Not completely getting what your telling me.
Have a breakpoint in my function SubmitCall() on the row "return true;" at the start of the procedure but that one is never hit.
Script changed to:
<script type="text/javascript"> function SendData() { $.ajax({ type: 'POST', url: '<%= ResolveUrl("~/CreateCall.aspx/SubmitCall") %>', data: '{}', contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (response) { alert("success"); }, error: function(response) { alert("Error"); } }); }; </script>
Result is that I get the message "Success" but breakpoint in method is not hit.
This problem looks basic but gives me a headache at the moment.
Tuesday, September 13, 2016 2:15 PM -
User-1142886626 posted
Hi Ernst Jan,
Result is that I get the message "Success" but breakpoint in method is not hit.According to your description and codes, we couldn’t directly find the reason why causes this issue.
I suggest you could use developer tool (press F12 in IE8 or above for example) to check the ajax post request is successfully.
You could use browser developer tool’s network tag to see the details information.
More details about how to use it, you could refer to follow link and images:
Following link about how to use it.
https://msdn.microsoft.com/en-us/library/gg130952(v=vs.85).aspx
Best regards,
Ailleen
Thursday, September 29, 2016 9:57 AM -
User-247642986 posted
Hi Ailleen,
Thanks for replying. I changed the process in a way that I did not need the call to the C# function from JQuery.
But your information wil help me in the future to solve problems.
Kind regards,
Ernst Jan
Friday, September 30, 2016 10:08 AM