This code will help you when you need to define a method code-behind and want to call that method from the client side. jQuery has made life simple. There is a very easy way to do this.
Earlier, we knew one way that we needed to add our method as a WebMethod
if we wanted to call a method from the code-behind at the client side. Using this method, we can do it without calling our method in a WebMethod
.
In this example, I am writing a method to delete a particular user when the Delete key is hit. I don't want a postback so I want the event to execute on the client side. I write a Delete
method on the server side in the CS file and call it from the client side using jQuery. The name of my page is Test.aspx.
This is my method in the CS file with the name DeleteRec()
.
private void DeleteRec()
{
int ID= Request.Form["ID"].ToString().ToInteger();
int UserID = Request.Form["UserID "].ToString().ToInteger();
UserBO lObjUserBO = new UserBO ();
lObjUserBO .DeleteUser(ID, UserID );
}
Here is how we call the method on page load:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
#region Ajax methods
if (Request.Form["MethodName"] == "DeleteR")
{
DeleteRec();
return;
}
#endregion
}
}
This is what we need to add at the client side (Test.aspx).
<a id="adelete" href="java<!-- no -->script:void(0);">Delete</a>
Use the following script to call the server side method when this anchor tag is clicked:
$('#adelete').click(function()
{
var dataToSend={ID:ID,MethodName:'DeleteR',UserID :UserID };
var options =
{
url: '<%=ResolveUrl("~/Test.aspx") %>?x=' + new Date().getTime(),
data: dataToSend,
dataType: 'JSON',
type: 'POST',
success: function (response) {
window.location.href='<%=ResolveUrl("~/Test1.aspx")%>/'+ID;
}
}
$.ajax(options);
});
Hope you find it useful, when trying to call a server side method client side.
I have keen interest in learning new things, exploring more on a topic and being more versatile