简体   繁体   中英

prevent postback in js for a webform dropdown

I am developping an asp.net webform application. In a page, I have a dropdown containing some values ("a","b","c",...). When I select a value in this dropdown, a server side event is raised and I write the selected value in my DB. This is the code :

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


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

This is working perfectly, but now I would like to ask a confirmation on my client side when a value is selected, does we really want to update the value in my db. If we selected yes in my confirm dialog in js, we pursue and call the server like before, if not we stop the postback. But this is what I am not able to do, I can't stop the postback, this is what i've tried :

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

None of these solutions worked, the server side function is called whatever I put, I think that is because of my autpostback="true" on my drodown, but if I remove this, then I will be in the opposite problem, and my server side function will never be called.

Thanks in advance for your help

You may try this:

  1. Make ClientIDMode="Static" to asp net dropdown so that you will have static id "myDdl" and also set autopostback to false

  2. In confirmornot method instead of return statement, try __doPostBack('myDdl');

i Have a hacky solution for you

HTMl

Add a hidden field

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

DDL Markup

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

In Cs

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


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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