Call server methods with JavaScript events


Sometimes, will be usefull call some server methods after detect an event. For example, click on a button, select a value in dropdownlist.
With the framework controls we can do this kind of actions (default events implemented), but what happen if we  want control other events like “type a value”, “make double click”, etc.
To manage this events we need to manage trough javascript and if we want to invoke a server method, one solution should be call WebMethod through ajax (http://api.jquery.com/jquery.ajax/).
Exists an easy way to do that without jquery ajax. We can associate a javascript event with a server method.
To do that we need to register the event in the Page_Init method and assign them to the control. We register the control and his events.
var onBlurScript = Page.ClientScript.GetPostBackEventReference(TxtJsEvntBox, "OnDblClick");
TxtJsEvntBox.Attributes.Add("ondblclick", onBlurScript);

var onKEyPress = Page.ClientScript.GetPostBackEventReference(TxtJsEvntBox, "OnKeyUp");
TxtJsEvntBox.Attributes.Add("onkeyup", onKEyPress);
The next step is manage the control and the event that has been triggered in Page_Load.
var ctrlName = Request.Params[Page.postEventSourceID];
var args = Request.Params[Page.postEventArgumentID];
HandleCustomPostbackEvent(ctrlName, args);
After that we need to design the logic of the server method for each event previously defined, for example like this:
if (ctrlName == TxtJsEvntBox.UniqueID) {
  switch (args) {
    case "OnDblClick":
      LblTest.Text = "On Double Click Event at " + DateTime.Now; break;
    case "OnKeyUp":
      LblTest.Text = "On Key Up Event at " + DateTime.Now;
      ScriptManager.RegisterStartupScript(this, GetType(), "focus", GetFocus(ctrlName.Replace('$', '_')), true);
      break;
  }
}
Maybe this is more easy to understand and implement if you not are familiarized with javascript or jquery language. You can download the full example here.

Leave a Reply

Your email address will not be published. Required fields are marked *