Call code-behind function from java script in c# - asp.net

Is it even possible? To call a code-behind c# function from java script in a visual web part?
It is a complex function so converting all codes to client side is not an option.
I want the logic that is there in this function to happen without a page refresh.
Thanks.

We can call a method in codebehind from the JQuery AJAX call and depending upon the status whether it is error or success the corresponding method will be executed.
function MyMethod() {
$.ajax({
type: "POST",
url: "CodeBehind.aspx/ClearData",
contentType: "application/json;charset=utf-8",
data: '',
dataType: "json",
success: function (data, textStatus) {
closePopUpwindow1();
},
error: function (data, textStatus) {
closePopUpwindow2();
}
});}
[WebMethod]
public static void ClearData(){
Page.SetGridSessionData(gridID, null);
}
If the server side method is successfully executed then closePopUpwindow1 method is executed else closePopUpwindow2 method will be executed.

You can use j Query ajax to call server side method and get the response to be used in java script.
This article has simple and good example to show what you need to do.
public partial class _Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
Java script
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}

Related

call a static method in User Control from js or ajax

I am trying to call a static method in User Control from js or ajax.
It is possible to do this if the code method lies directly in WebForm but it is not possible to do it if we put the code method in UserControl and then put this UserControl in a WebForm.
Code Behind:
[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public static string GetNameFromCodeBehind (string name)
{
return "Hello from Code-Behind, " + name ;
}
AJAX Code:
$.ajax({
type: "POST",
url: "MyUserControl.ascx/GetNameFromCodeBehind",
data: JSON.stringify({ name: "Anton" }),
contentType: "application/json; charset=utf-8",
dataType: "json",
processdata: true,
success: function (data) {
alert(data.d);
},
error: function (e) {
alert(e.statusText)
}
});
Ajax Error:
Not Found
If GetNameFromCodeBehind is inside MyUserControl.ascx, then it will be able to find a URL. Moreover, you have written the name of static method as callFromCodeBehind. So, you need to write the URL sccordingly

how to use jQuery ajax with asp.net user controls?

I want to use ajax with asp.net user control,
$.ajax({
type: "POST",
url: "*TCSection.ascx/InsertTCSection",
data: "{id:'" + id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var URL = msg.d;
alert(URL);
});
.cs code
[WebMethod]
public static string InsertTCSection(string id)
{
string result = "deneme";
return result;
}
You cannot call a method kept inside a usercontrol through jquery.
because .ascx controls don't represent real url.
They are meant to be embedded in some ASP.NET page, hence they don't exist at runtime.
what you might do is, to create a separate service and place your method there.
like webservices.
see this, this and many others
i am using generic Handler to solve this problem.
Try:
$.ajax({
type: "POST",
url: "*TCSection.ascx/InsertTCSection",
data: JSON2.stringify({ id: id}, //Your 2nd id is passing value but i dont know where its come from
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var URL = msg.d;
alert(URL);
}
)};
and in cs:
[WebMethod]
public static string InsertTCSection(string id)
{
string result="deneme";
return result;
}
I think you might be missing this attribute
[System.Web.Script.Services.ScriptService]
Before you service class as
[System.Web.Script.Services.ScriptService]
public class TCSection: System.Web.Services.WebService
{
[WebMethod]
public static string InsertTCSection(string id)
{
}
}
Or there may be one other reason that path of the webservice is not right.

webservice not returning values to on jquery ajax request

I would like consume cross-domain web-service from client with jquery.here is my code
function getId() {
var testid = ($('#<%=PreviousTest.ClientID %> OPTION:selected').val());
jQuery.support.cors = true;
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType:"json",
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
}
my webservice returns values in this format
{"Table":[{"minlatency":16.0,"Time":"/Date(1328248782660+0530)/"},{"minlatency":7.0,"Time":"/Date(1328248784677+0530)/"},{"minlatency":13.0,"Time":"/Date(1328248786690+0530)/"},{"minlatency":6.0,"Time":"/Date(1328248788690+0530)/"},{"minlatency":20.0,"Time":"/Date(1328248790707+0530)/"},{"minlatency":12.0,"Time":"/Date(1328248792723+0530)/"},{"minlatency":26.0,"Time":"/Date(1328248794723+0530)/"},{"minlatency":18.0,"Time":"/Date(1328248796723+0530)/"}]}
Calls in cross-domain work in a different way. They create dynamic javascripts that are inserted to the page using a callback function. This function is used to handle the response from the service. The Jquery calls add a "?callback=?" to the URL of the service, where "callback" is the name of the function that will be inserted.
To call cross-domain services with JQuery you have to do the following:
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp", //The data type that you must use is JSONP. Basically tells JQuery that the request is cross-domain
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
},
jsonpCallback: 'callback' //Dude to the fact that the JS is being generated dynamicaly, this tells JQuery to use the name "callback" for the function that will handle the result, as it adds "?callback=?" to the URL
});
You could also use "jsonp" instead of "jsonpCallback" if you want to "override the callback function name in a jsonp request" (from JQuery).
It worked for me (in WCF REST services which communicate with JSON messages, but it should work the same way in your case). This is all explained in the JQuery Ajax documentation.
Hope this helps.

jQuery + ASP.NET 4.0 ajax page method not working

I have used whole lots of options resolving this, but it is not working.
My breakpoint is not hit in the Web Method. Also, the success function is being called, however, entire page content is returned not the string "hello".
My page does not at all use asp.net ajax scriptmanager. It uses plain jQuery only. I am using ASP.NET 4.0.
In brief, my page method is defined as:
[WebMethod]
public static string Populate()
{
return "hello";
}
The ajax call is:
$.ajax({
url:'WebForm3.aspx/Populate',
data:{},
dataType:"json",
type:"GET",
success: function(msg) {
alert("success");
},
error: function(msg, text) {
alert(text);
}
});
Page methods only work when POSTed to, like this:
$.ajax({
url:'WebForm3.aspx/Populate',
data: '{}',
dataType:"json",
type:"POST",
contentType: 'application/json; charset=utf-8',
success: function(msg) {
alert("success"); },
error: function(msg, text) {
alert(text);
}
});
Don't forget to quote the data argument: data: '{}'.

using jQuery AJAX with asp.net webservices always goes to error: instead of success:

Issue
I have an aspx page with jQuery code to send an ajax request over to an asmx web service file (on the same website). The response that comes back is not consistent, however, it consistently fires the "error" jQuery callback as opposed to the "success" call back. The status code inconsistently varies between 200, 12030, and 12031. The responseText of the message to the callback inconsistently varies between [blank] and the actual XML that the json webservice returns. I debugged the code, and the webservice does actually execute without any exceptions.
ASPX Code
//Code omitted for brevity
<script type="text/javascript">
jQuery(document).ready(function()
{
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CallDequeue.asmx/Dequeue",
data: "{}",
dataType: "json",
success: function(Msg)
{
alert('success:' + Msg.responseText);
},
error: function(Msg)
{
alert('failed:' + Msg.status + ':' + Msg.responseText);
}
});
});
</script>
//Code ommitted for brevity
Web Service Code
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class CallDequeue : System.Web.Services.WebService
{
[WebMethod]
public string Dequeue()
{
return "{\"d\":{\"FirstName\":\"Keivan\"}}";
}
}
When you mark the service as a ScriptService, it automatically handles the JSON serialization. You shouldn't manually serialize the response.
If you want the return to come back as "FirstName", then you can use a DTO class to control the syntax. Just returning a string, it would come back as {'d':'Keivan'} instead of {'d':{'FirstName':'Keivan'}}.
[ScriptService]
public class CallDequeue : System.Web.Services.WebService
{
public class PersonDTO
{
public string FirstName;
}
[WebMethod]
public PersonDTO Dequeue()
{
var p = new PersonDTO();
p.FirstName = "Keivan";
return p;
}
}
A few changes to the calling syntax:
jQuery(document).ready(function() {
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "CallDequeue.asmx/Dequeue",
data: "{}",
dataType: "json",
success: function(Msg) {
// Unless you're using 2.0, the data comes back wrapped
// in a .d object.
//
// This would just be Msg.d if you return a string instead
// of the DTO.
alert('success:' + Msg.d.FirstName);
},
error: function(Msg) {
alert('failed:' + Msg.status + ':' + Msg.responseText);
}
});
});
You can read more about ASP.NET AJAX's .d wrapper here, if you're interested.
Update:
Using ASP.NET 2.0, you need to install the ASP.NET AJAX Extensions v1.0. Additionally, make sure your web.config is configured for ASP.NET AJAX (most specifically the HttpHandlers section).
This question will most likely help you.
Otherwise, I converted this web service to a page method and it worked immediately. Do you have that option?
CS:
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string Dequeue()
{
return "{\"d\":{\"FirstName\":\"Keivan\"}}";
}
}
ASPX:
<script type="text/javascript">
jQuery(document).ready(function()
{
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "test.aspx/Dequeue",
data: "{}",
dataType: "json",
success: function(Msg)
{
alert('success:' + Msg.responseText);
},
error: function(Msg)
{
alert('failed:' + Msg.status + ':' + Msg.responseText);
}
});
});
Check this and other Encosia articles out for more information.
you say it's json, but it returns xml. i see a slight disconnect there.
Such a simple answer. My web.config wasn't ajax enabled so all calls (regardless of my webservice being a scriptservice) were returning XML instead of pure json.
Try marking up your web method with [ScriptMethod]
As in:
[WebMethod]
[ScriptMethod]
My thanks to all the responders here.
Be sure to add these attributes in front of the methods to be used
[WebMethod]
[ScriptMethod]
Not sure when the ScriptMethod is needed ?
Curiously, he did NOT have the [Script Service] and the [WebMethod] in his download code.
Anyway, the aJax 500 12030 12031 errors are gone after the above changes.

Resources