Postback from JavaScript
Calling postback event from Javascript in ASP.NET | ASP.NET Postback with Javascript | Tigger postback from javascript | Postback in asp.net
Hello today we will see how we can trigger a postback in ASP.NET from the clientside using javascript.
We tend to require this many times when we code applications! We will do it using Page.GetPostBackEventReference.
Simply use the below code.
Javascript Code
function SomeFunction()
{
if(some condition when you want to trigger postback)
{
// trigger postback
<%= this.Page.GetPostBackEventReference(this,"Delete")%>
}
else
{
// some other code execution
}
}
C# Codebehind Code
protected void Page_Load(object sender, EventArgs e)
{
string eventArg = Request[ "__EVENTARGUMENT" ];
// if null or empty
if (!String.IsNullOrEmpty(eventArg))
{
switch(eventArg)
{
case "Delete":
DeleteMethod();
break;
case "Update":
UpdateMethod();
break;
case "CreateNew":
CreateNewMethod();
break;
}
}
}
private void CreateNewMethod()
{
}
private void UpdateMethod()
{
}
private void DeleteMethod()
{
}
In the code behind, eachtime a postback takes place it will check on Page Load whether the postback was triggered by javascript code.
If yes, then based on the eventArg value it will decide which action (method) to trigger.
In the above example the DeleteMethod() will get called as the key passed from javascript is "Delete".
Based on the key you can decide which codebehind method you wish to call and execute.
I tried to stick to the point and make it as simple as possible :)
Hope it was helpful :)
Currently rated 3.0 by 1 people
- Currently 3/5 Stars.
- 1
- 2
- 3
- 4
- 5