Pass C# object to webmthod through ajax
Ajax is frequently used in ASP.NET to pass data from javascript to c# methods known as WebMethod in webforms. It is easy to pass common data like string or int values to webmethod through ajax.
Sometimes we need to pass whole object of some C# class thorugh ajax to avoid sending and receiving large number of parameters. Lets take an example where we will send UserInfo object from ajax to webmethod.
This is our class whose object will be sent through ajax
And here is webmthod in which we will receive the UserInfo object
And Here is our ajax method
Here is object received
Sometimes we need to pass whole object of some C# class thorugh ajax to avoid sending and receiving large number of parameters. Lets take an example where we will send UserInfo object from ajax to webmethod.
This is our class whose object will be sent through ajax
public class UserInfo
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Address { get; set; }
}
And here is webmthod in which we will receive the UserInfo object
[System.Web.Services.WebMethod]
public static void GetUserInfo(UserInfo User)
{
//Your Code
//Your Code
}
And Here is our ajax method
var objUser = new Object();
objUser.UserId = 1;
objUser.UserName = "Mairaj";
objUser.Address = "Street 10";
$.ajax({
cache: false,
type: "POST",
contentType: "application/json;
charset=utf-8",
url: "User.aspx/GetUserInfo",
data: JSON.stringify({ User:
objUser }),
dataType: "json",
success: function (data) {
console.log("Success");
},
error: function (err) {
console.log(err.responseText);
}
});
Here is object received
Comments
Post a Comment