Inline javascript does not work after async postback from UpdatePanel

I created a server control where I embedded some JavaScript files. This works fine, but when the server control is placed in the ajax UpdatePanel, it stops working after the asynchronous postback starts in the update panel.

Here is my code in the server:

protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); ClientScriptManager clientScriptManager = Page.ClientScript; const string DATE_TIME_PICKER_JS = "JQueryControls.Scripts.DateTimePicker.js"; clientScriptManager.RegisterClientScriptResource(typeof(DateTimePicker), DATE_TIME_PICKER_JS); if (Ajax.IsControlInsideUpdatePanel(this) && Ajax.IsInAsyncPostBack(Page)) { Ajax.RegisterClientScriptResource(Page, typeof(DateTimePicker), DATE_TIME_PICKER_JS); } } 

Ajax is the class from this link .

If this code is executed in async postback:

 public static void RegisterClientScriptResource(Page page, Type type, string resourceName) { object scriptManager = FindScriptManager(page); if (scriptManager != null) { System.Type smClass = GetScriptManagerType(scriptManager); if (smClass != null) { Object[] args = new Object[] { page, type, resourceName }; smClass.InvokeMember("RegisterClientScriptResource", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod, null, null, args); } } } 

Any ideas on how to make this work in UpdatePanel?

+4
source share
1 answer

UpdatePanels make new items appear on the page when they are submitted. This is no longer the same element, so your bindings are no longer used. If you use jQuery and bind events together, you can use their live API, found here . Otherwise, for things like datepickers, this fire will once and fundamentally change the functionality of the element that you need in order to run some javascript after loading new elements; all this requires binding some javascript calls to the callback function provided by Microsoft:

 function BindEvents() { //Here your jQuery function calls go } var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(BindEvents); 

Edit: based on your comment, I would make a DatePicker.js file as follows:

 $(document).ready(function () { // Call BindDatePicker so that the DatePicker is bound on initial page request BindDatePicker(); // Add BindDatePicker to the PageRequestManager so that it // is called after each UpdatePanel load var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_endRequest(BindDatePicker); }); // We put the actual binding of the DatePicker to the input here // so that we can call it multiple times. Other binds that need to happen to the // elements inside the UpdatePanel can be put here as well. var BindDatePicker = function() { $('.DatepickerInput').datepicker({ showAnim: 'blind', autoSize: true, dateFormat: 'dd-mm-yy' }); }; 
+4
source

Source: https://habr.com/ru/post/1380741/


All Articles