【问题标题】:prevent postback in js for a webform dropdown防止在 js 中回发 webform 下拉列表
【发布时间】:2016-03-24 13:27:09
【问题描述】:

我正在开发一个 asp.net webform 应用程序。在一个页面中,我有一个包含一些值(“a”、“b”、“c”、...)的下拉列表。当我在此下拉列表中选择一个值时,会引发一个服务器端事件,并将所选值写入我的数据库中。 这是代码:

<asp:DropDownList ID="myDdl" runat="server" OnSelectedIndexChanged="server_handler" AutoPostBack="True"/>


protected void server_handler(object sender, EventArgs e)
{
    myUpdateMethod(this.myDdl.selectedValue);
}

这工作得很好,但是现在我想在选择一个值时询问我的客户端确认,我们真的要更新我的数据库中的值吗? 如果我们在 js 的确认对话框中选择了是,我们会像以前一样继续调用服务器,如果不是,我们停止回发。但这是我无法做到的,我无法停止回发,这是我尝试过的:

 <asp:DropDownList ID="myDdl" runat="server" OnSelectedIndexChanged="server_handler" AutoPostBack="True" onchange="confirmornot(event)"/>


function confirmornot(event)
{
    var str = confirm("do you want to continue?")
    if (!str)// the user select no and this is where I am trying to stop to calling the server handler function. Basically there, I want here nothing to happen
    {
        //solution 1
        event.preventDefault();
        //solution 2
        event.stopPropagation() or event.stopImmediatePropagation()
        //solution 3
        return false or return true 
    }

这些解决方案都不起作用,无论我放什么都会调用服务器端函数,我认为这是因为我的 autpostback="true" 在我的下拉菜单中,但如果我删除 这样,我就会遇到相反的问题,并且永远不会调用我的服务器端函数。

提前感谢您的帮助

【问题讨论】:

  • 回发由 __doPostBack js 完成,您可以在 onchange
  • 谢谢,效果很好。

标签: javascript c# jquery asp.net webforms


【解决方案1】:

你可以试试这个:

  1. 将 ClientIDMode="Static" 设置为 asp 网络下拉列表,这样您将拥有静态 id "myDdl" 并将自动回发设置为 false

  2. 在confirmornot方法而不是return语句中,试试 __doPostBack('myDdl');

【讨论】:

    【解决方案2】:

    我有一个 hacky 解决方案给你

    HTML

    添加隐藏字段

    <asp:HiddenField runat="server" ID="hdntocheck" />
    

    DDL 标记

    <asp:DropDownList ID="myDdl" runat="server" OnSelectedIndexChanged="server_handler" AutoPostBack="True" onchange="confirmornot()"/>
    

    Js

        function confirmornot() {
    
            if (!confirm("do you want to continue?"))
            {
                hdntocheck.value = "false";
    
            }
            else {
                hdntocheck.value = "true";
            }
        }
    

    在 Cs 中

    protected void server_handler(object sender, EventArgs e)
    {
    if( hdntocheck.value =="true")
      {
      myUpdateMethod(this.myDdl.selectedValue);
      }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-06
      • 2020-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多