Can we call C# code behind using jQuery?
Nitin Choudhary
Yes we can call C# Web method from Jquery. Like - $.ajax({type: "POST",url: "Default.aspx/WebMethodName",data: '{}',contentType: "application/json",dataType: "json",success: function (data) {},error: function (x, e) {alert("The call to the server side failed. " + x.responseText);}})
YES
Yes,But it having some prerequisiteC# method mark as webmethod. Webmethod should be public. Webmethod also be static.[webmethod] Public static YourMethodName( parameter... ) { } for your knowledge this method call in two ways one way is Using PageMethods.YourMethodName( Parameter, OnSuccess ,OnFailure ). For this way you required to add on page.Second way using Jquery Ajax.Sorry for spelling mistake.
$.ajax({ type: "POST", url: "Default.aspx/WebMethodName", data: '{}', contentType: "application/json", dataType: "json", success: function (data) {}, error: function (x, e) { alert("The call to the server side failed. " + x.responseText); } })and your method should be [webmethod] public static string WebMethodName() { return "success";}
We can call a Web method using ScriptManager as well. & In javascript, PageMethods.(parameters, onSuccess, onFail);
Is it only work with web method?
use Jquery.Ajax$.ajax({url: "test.html",context: document.body }).done(function() {$( this ).addClass( "done" ); });
Yes, we can call C# web method from Jquery for Exmple JavaScript code$.ajax({type: "POST",url: "CS.aspx/GetName",data: '{name: abcd }',contentType: "application/json; charset=utf-8",dataType: "json",success: OnSuccess,failure: function(response) {alert(response.d);}});}function OnSuccess(response) {alert(response.d);}C#[System.Web.Services.WebMethod]public static string GetName(string name){return "Hello " + name ; }
Yes, we can call C# code from jQuery as it supports .net application