防止在js中回发webform下拉列表

prevent postback in js for a webform dropdown

本文关键字:webform 下拉列表 js      更新时间:2023-09-26

我正在开发一个asp.net网络表单应用程序。在一个页面中,我有一个包含一些值("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 
    }

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

提前感谢您的帮助

你可以试试这个:

  1. 将ClientIDMode="Static"设为asp net下拉列表,这样您就可以拥有Static id"myDdl",并将autopostback设置为false

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

i为您提供了一个破解的解决方案

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

}