繁体   English   中英

从UpdatePanel进行异步回发后,嵌入式javascript无效

[英]Embedded javascript does not work after async postback from UpdatePanel

我已经创建了一个服务器控件,我已经嵌入了一些JavaScript文件。 这可以正常工作,但是当服务器控件放在ajax UpdatePanel中时,它会在updatepanel中触发异步回发后停止工作。

这是我在服务器控件中的代码:

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是这个链接的一个

在异步回发上执行此代码的位置:

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);
        }
    }
}

有关如何在UpdatePanel中使用此功能的任何想法?

UpdatePanels会导致新元素在发回时放置在页面中。 它不再是相同的元素,因此您的绑定不再适用。 如果您正在使用jQuery并将事件绑定在一起,则可以使用此处live API。 否则,对于诸如datepickers之类的东西,它会触发一次并从根本上改变项目的功能,一旦加载新元素,你需要激活一些javascript; 所有这些都需要将一些javascript调用绑定到Microsoft提供的回调函数:

function BindEvents()
{
    //Here your jQuery function calls go
}

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(BindEvents);

编辑:根据您的评论,我会像这样制作DatePicker.js文件:

$(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'
    });
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM