简体   繁体   中英

Dropdown menu SelctIndexChange not working as expected

//master.cs     
protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
    //alert box
            string message = "Some Content of the Site are only in English. Do you want to continue?";
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("return confirm('");
            sb.Append(message);
            sb.Append("');");
            Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "alert", sb.ToString());
       //alert end
            //Sets the cookie that is to be used by Global.asax
            HttpCookie cookie = new HttpCookie("CultureInfo");
            cookie.Value = ddlLanguage.SelectedValue;
            Response.Cookies.Add(cookie);

            //Set the culture and reload the page for immediate effect. 
            //Future effects are handled by Global.asax
            Thread.CurrentThread.CurrentCulture = new CultureInfo(ddlLanguage.SelectedValue);
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddlLanguage.SelectedValue);
            Server.Transfer(Request.Path);
    }

//master  Page
<asp:DropDownList ID="ddlLanguage" class="langpnl" runat="server" AutoPostBack="True" 
        OnSelectedIndexChanged="ddlLanguage_SelectedIndexChanged">
        <asp:ListItem Value="en-US">Eng</asp:ListItem>
        <asp:ListItem Value="es-ES">Esp</asp:ListItem>
    </asp:DropDownList>

Whenever the user changes from English to Spanish I want to display an alert box. Its a weird behavior, this code is not working its not showing me any alert box on selected index change but if I paste the alert box code in the page load event it works. Is the pageload has to do anything with this? Secondly is it possible to remember the answer ie if the user selects an checkbox saying remember me, I should remember whether the user selected YES or NO throughout the session. any suggestions on the second questions will help. But please help me find the reason why the above code is not working as expected.

Try the following code in your dropdownSelected index changed event to show the alert box

if (!ClientScript.IsStartupScriptRegistered("JSScript"))
            {
                //give the exception details in a alert box
                string sb = string.Format(@"<script>alert('{0}');</script>'", "Message to be shown");
                ClientScript.RegisterStartupScript(this.GetType(), "JSScript", sb);
            }

Register javascript event with onchange="return CheckLanguage(this);" instead of ClientScript.RegisterStartupScript .

HTML

<asp:DropDownList ID="ddlLanguage" onchange="return CheckLanguage(this);" class="langpnl" runat="server" AutoPostBack="True" 
        OnSelectedIndexChanged="ddlLanguage_SelectedIndexChanged">
        <asp:ListItem Value="en-US">Eng</asp:ListItem>
        <asp:ListItem Value="es-ES">Esp</asp:ListItem>
    </asp:DropDownList>

Javascript

<script Type="text/javascript>

function CheckLanguage(ddl)
{
    return confirm("Are you sure to change language");
}

</script>

your event handler is not working as expected due to this ligne

Server.Transfer(Request.Path);

remove it if possible or try a work arround, and everything will be ok

EDIT :

To get by the issue caused by Server.Transfer try this and see if it makes sens

in your aspx file

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

in your code behind

protected void Page_Load(object sender, EventArgs e)
{
    if (hide.Value == "true")
    {
        Server.Transfer(Request.Path);
    }
    hide.Value = "";
}   

protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
    ...

    sb.Append("if(confirm('")
     .Append(message)
     .Append("')){")
     .AppendFormat("document.getElementById('{0}').value = 'true'", hide.ClientID)
     .Append("}");

     ...

     Thread.CurrentThread.CurrentCulture = new CultureInfo(ddlLanguage.SelectedValue);
     Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddlLanguage.SelectedValue);                
 }

You are sending the user to a new page before they have a chance to confirm. Server.Transfer requests a new page (even though it's the same url) so your js never gets written to the page. You need to run the confirm js before the postback ever happens.

I don't think you can prevent the SelectedIndexChanged postback either, as dot net adds it's own js event handlers to accomplish that. I think the least obtrusive method here to make a new button, move the language handler code to the button's click handler, then use client side js to click the button when the user confirms their choice.

    <asp:DropDownList ID="ddlLanguage" class="langpnl" runat="server" AutoPostBack="False">
        <asp:ListItem Value="en-US">Eng</asp:ListItem>
        <asp:ListItem Value="es-ES">Esp</asp:ListItem>
    </asp:DropDownList>
    <asp:Button ID="myHiddenButton" runat="server" Style="display: none;" OnClick="myHiddenButton_Click" />


void Page_PreRender(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string message = "Some Content of the Site are only in English. Do you want to continue?";
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append("if confirm('");
        sb.Append(message);
        sb.Append("') ");
        sb.AppendFormat("document.getElementById('{0}').click();", this.myHiddenButton.ClientID);

        //Page.ClientScript.RegisterOnSubmitStatement(this.GetType(), "alert", sb.ToString());

        // write your js as the client-side onchange handler on the ddl
        this.ddlLanguage.Attributes["onchange"] = sb.ToString();

        //alert end
    }

    this.myHiddenButton.Click += new EventHandler(myHiddenButton_Click);
}

void myHiddenButton_Click(object sender, EventArgs e)
{
    // only ever called if user confirms the js prompt

    //Sets the cookie that is to be used by Global.asax
    HttpCookie cookie = new HttpCookie("CultureInfo");
    cookie.Value = ddlLanguage.SelectedValue;
    Response.Cookies.Add(cookie);

    //Set the culture and reload the page for immediate effect. 
    //Future effects are handled by Global.asax
    Thread.CurrentThread.CurrentCulture = new CultureInfo(ddlLanguage.SelectedValue);
    Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddlLanguage.SelectedValue);
    Server.Transfer(Request.Path);
}

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