ClientScript.GetPostBackEventReference
ClientScript.RegisterStartupScript
__doPostBack
ClientScript.GetPostBackEventReference: Returns a string that can be used in a client event to cause postback to the server.
ClientScript.RegisterStartupScript: Registers the startup script with the Page object.
_doPostBack: It is ASP.NET's way of doing javascript postbacks . The first argument is eventTarget, which is the control that is triggering the action. The second argument is event args means any additional information you might want to send with your postback.
Below is the sample code:
<%@ Page Language="C#" %>
Let's start with button's click handler first:
protected void btnFoo_OnClick(object sender, EventArgs e)
{
//Do your stuff here.....
//Below is the code to initiate the modal
var sb = new StringBuilder();
sb.AppendFormat("var foo = window.confirm('Do you want to proceed ?');\n");
sb.Append("if (foo)\n");
sb.Append("__doPostBack('MyConfirmationPostBackEventTarget', foo);\n");
ClientScript.RegisterStartupScript(GetType(), "MyScriptKey", sb.ToString(), true);
}
This is the point where we decide to throw confirm box logic to the client. Here I have made the string to be rendered to the client as JS code. Now when the user presses OK in the confirm box _doPostBack method will called in JavaScript and postback will take place and this is due to ClientScript.GetPostBackEventReference(this, string.Empty) which we wrote in Page Load. Now let's move to the code which will be fired during the next postback (you can say after clicking OK of confirm box)
if (IsPostBack)
{
string eventTarget = Request["__EVENTTARGET"] ?? string.Empty;
string eventArgument = Request["__EVENTARGUMENT"] ?? string.Empty;
switch (eventTarget)
{
case "MyConfirmationPostBackEventTarget":
if (Convert.ToBoolean(eventArgument))
{
AfterUserConfirmationHandler();
}
break;
}
}
Now remember the "__doPostBack('MyConfirmationPostBackEventTarget', foo)" which we called. Here "MyConfirmationPostBackEventTarget" is the event target and "foo" is the event args. So in the server side we checked if it is post back, event target is "MyConfirmationPostBackEventTarget" and eventArgument is true we will fire our server side code. That's it we are done with our task which we need to perform.
No comments:
Post a Comment