简体   繁体   中英

How to change drop down list selected index and visibility using another drop down list in asp.net?

I have a drop down list like this in my asp.net application,

<asp:DropDownList runat="server" ID="ddlChanges" CssClass="selectstyle" onchange="javascript:ddlChangesChanged();"> 
<asp:ListItem Text="-- Select -- " Value="-1"></asp:ListItem> 
<asp:ListItem Text="Status Change" Value="1"></asp:ListItem>
<asp:ListItem Text="Product Name Change" Value="2"></asp:ListItem>       
<asp:ListItem Text="Category Change" Value="3"></asp:ListItem>
</asp:DropDownList>

So, when user selects "Status Change" from the list, another dropdown list with following values appears,

<asp:DropDownList runat="server" ID="ddlStatus" CssClass="selectstyle"  Style="visibility: hidden;"> 
<asp:ListItem Text="-- Select -- " Value="-1"></asp:ListItem> 
<asp:ListItem Text="Pending" Value="1"></asp:ListItem>
<asp:ListItem Text="Fixed" Value="2"></asp:ListItem>       
<asp:ListItem Text="Cancelled" Value="3"></asp:ListItem>
</asp:DropDownList>

<asp:Button ID="btnUpdate" CssClass="selectstyle" runat="server" Text="Update" OnClick="btnUpdate_Click"></asp:Button>

If user does not select any value from the drop down list (ddlStatus), I am displaying an alert message ("You must select a status.") using JavaScript in the btnUpdate click event,

if (this.ddlStatus.SelectedItem.Value.Trim() == "-1")
{
    string script = "<script type=\"text/javascript\">alert('You must select a status.');</script>";
    ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script);
}

But after this, my page refreshes and drop down list ddlChanges has "Status Change" (previously selected item) as selected item and drop down list (ddlStatus) gets hidden. I want ddlChanges drop down list to have -- Select -- as the selected item and ddlStatus should be visible.

How can I do that?

You are doing a full postback (all changes on client get reset, except the posted back input values) - so either do a client (javascript) validation (best option), or switch to ajax partial postback (faster option), or simply just change this (slowest option):

if (this.ddlStatus.SelectedItem.Value.Trim() == "-1")
{
    ddlStatus.Attributes["style"] = null;
    string script = "<script type=\"text/javascript\">alert('You must select a status.');</script>";
    ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script);
}

btnUpdate click event raises the server side code, and the server does not know about what the user has selected on client. one option could be use client side validation to avoid Post back and preserve the selections at client

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