使用 JavaScript 或 jQuery 手动更新 UpdatePanel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3490457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:52:20  来源:igfitidea点击:

Update an UpdatePanel manually using JavaScript or jQuery

javascriptjqueryasp.net.netupdatepanel

提问by Rush Frisby

Is it possible to update an UpdatePanel manually using JavaScript or jQuery?

是否可以使用 JavaScript 或 jQuery 手动更新 UpdatePanel?

What I have is a TextBox at the top of my page. When a user leaves that TextBox I want to run some server code (it will add a record to my database) then at the bottom of the page I have an UpdatePanel which will get refreshed. The UpdatePanel has a GridView which will have an entry for the record added)

我的页面顶部有一个文本框。当用户离开该 TextBox 时,我想运行一些服务器代码(它将向我的数据库添加一条记录),然后在页面底部我有一个 UpdatePanel,它将被刷新。UpdatePanel 有一个 GridView,它将添加一个记录条目)

回答by Azhar

Just call this javascript function. Here UpdatePanel1 is updatepanel's ID

只需调用此 javascript 函数即可。这里 UpdatePanel1 是 updatepanel 的 ID

 <script type="text/javascript">

            var UpdatePanel1 = '<%=UpdatePanel1.ClientID%>';

            function ShowItems()
            {
               if (UpdatePanel1 != null) 
               {
                   __doPostBack(UpdatePanel1, '');
               }
            }       

        </script>

回答by Rush Frisby

I think I got my answer... have to create a hidden button in the UpdatePanel then call

我想我得到了答案......必须在 UpdatePanel 中创建一个隐藏按钮然后调用

__doPostBack('<%= Button.ClientID %>','');

回答by Culme

Although an old question, I think it deserves the mention of one more solution.

虽然是一个老问题,但我认为值得再提一个解决方案。

If you do not wish to rely on hidden buttons or the illusive __doPostBack, there is the option of "ClientScript.GetPostBackEventReference", as described on this (likewise rather old but still great) page:

如果您不想依赖隐藏按钮或虚幻的 __doPostBack,则可以选择“ClientScript.GetPostBackEventReference”,如本页所述(同样很旧但仍然很棒):

http://www.4guysfromrolla.com/articles/033110-1.aspx

http://www.4guysfromrolla.com/articles/033110-1.aspx

In short, if your UpdatePanel is declared like this:

简而言之,如果您的 UpdatePanel 声明如下:

<asp:UpdatePanel ID="MyUpdatePanel" runat="server">...</UpdatePanel>

then in JavaScript you can call the script that is generated by this server sidecode:

然后在 JavaScript 中,您可以调用由此服务器端代码生成的脚本:

ClientScript.GetPostBackEventReference(MyUpdatePanel, "")

So in your aspx page you could have something like this:

所以在你的 aspx 页面中,你可以有这样的东西:

function MyJavaScriptFunction(){
   doSomeStuff();
   <%=ClientScript.GetPostBackEventReference(MyUpdatePanel, "")%>
}

The code between <% and %> will be replaced with an actual javascript call when the page is parsed, so you can have a look at it by viewing the source code of the page in your browser.

解析页面时,<% 和 %> 之间的代码将替换为实际的 javascript 调用,因此您可以通过在浏览器中查看页面的源代码来查看它。

It may not be easier than the other replies, but I prefer it since it does not introduce any extra elements and __doPostBack feels like a hack. :-)

它可能并不比其他回复容易,但我更喜欢它,因为它没有引入任何额外的元素,而且 __doPostBack 感觉就像一个黑客。:-)

回答by Rony

Well, in my case the answer was the use of the UniqueID. ClientID did not work.

嗯,就我而言,答案是使用 UniqueID。客户端 ID 不起作用。

 __doPostBack("<%=btnTest.UniqueID %>", "");

This works perfectly. Don't ask me why.

这完美地工作。不要问我为什么。

回答by Marian Schutz

Create function for async postback:

为异步回发创建函数:

    function __doPostBackAsync(eventName, eventArgs) {
        var prm = Sys.WebForms.PageRequestManager.getInstance();

        if (!Array.contains(prm._asyncPostBackControlIDs, eventName)) {
            prm._asyncPostBackControlIDs.push(eventName);
        }

        if (!Array.contains(prm._asyncPostBackControlClientIDs, eventName)) {
            prm._asyncPostBackControlClientIDs.push(eventName);
        }

        __doPostBack(eventName, eventArgs);
    }

Call this function where you need (in click event, load event, ...):

在需要的地方调用此函数(在单击事件、加载事件中,...):

 __doPostBackAsync("UpdatePanel1", "");

In codebehind Page_Load check asynchronous postback and update desired UpdatePanel:

在代码隐藏 Page_Load 检查异步回发并更新所需的 UpdatePanel:

if (scriptManager.IsInAsyncPostBack)
{
      if (Request["__EVENTTARGET"] == UpdatePanel1.ID)
      {
         ...

         //Do update
         UpdatePanel1.Update();
      }
}

回答by itfake

You just need call change() on control witch you triggered in your updatePanel.

您只需要在 updatePanel 中触发的控件上调用 change()。

For example:

例如:

  <asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="updatePanel1" ChildrenAsTriggers="True">
    <ContentTemplate>
      <asp:DropDownList ID="ddl" runat="server" Visible="true" AutoPostBack="true" CssClass='someClass' />
    </ContentTemplate>
    <Triggers>
     <asp:AsyncPostBackTrigger ControlID="ddl" EventName="SelectedIndexChanged" />
    </Triggers>
  </asp:UpdatePanel


<script>          
  $(".someClass").change();
 </script>

回答by Alexandre N.

This works for me:

这对我有用:

<asp:UpdatePanel id="pnl" UpdateMode="Conditional" runat="server">
 <contentemplate>
    <div>...your content...</div>
     <div style="display: none; line-height: 0pt;">
        <asp:Button id="btnUpdate" runat="server" UseSubmitBehavior="false"  />
     </div>
</contentemplate>
</asp:UpdatePanel> 

JavaScript:

JavaScript:

function doUpdate()
{
  var btn = document.getElementById("<%#= btnUpdate.ClientID %>");
  if(btn != null) { btn.click(); }
}

回答by MaciejLisCK

ASPX:

ASPX:

<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="UpdatePanel1_OnLoad" > ...

CodeBehind:

代码隐藏:

protected void UpdatePanel1_OnLoad(object sender, EventArgs e)
{
    var rawArguments = Page.Request["__EVENTARGUMENT"];
    if(rawArguments != null)
    {
        var arguments = HttpUtility.ParseQueryString(rawArguments);

        switch (arguments["EventName"])
        {
            case "Event1":
                var parameter1Value = arguments["parameter1"];
                var parameter2Value = arguments["parameter2"];
                break;
        }
    }
}

Javascript:

Javascript:

function updatePanelPartialPostback(updatepanelId, eventName, parameters) {
    var parametersParsed = "EventName=" + eventName + "&";

    for (var propertyName in parameters) {
        parametersParsed += propertyName + '=' + parameters[propertyName] + '&';
    }

    __doPostBack(updatepanelId, parametersParsed);
}


updatePanelPartialPostback('<%= UpdatePanel1.ClientID %>', 'Event1', { parameter1: 'value1', parameter2: 'value2' });