aspx页面内的内联c#代码

时间:2014-01-29 22:27:47

标签: c# asp.net

我想根据userName变量显示不同的下拉选项,但不知道如何执行此操作。这是代码:

<form id="frmViewRequest" runat="server">
    <div class="widget-content">

       <div class="padd"><div class="row">
          <div class="col-md-2">
             <% if (userName == "jpublic"){
                <asp:DropDownList class="form-control" runat="server" AutoPostBack="true" ID="ddlChangeStatus">
                <asp:ListItem Text="Under Review" value="1" />
                </asp:DropDownList>
              }
              else{
                <asp:DropDownList class="form-control" runat="server" AutoPostBack="true" ID="ddlChangeStatus">
                <asp:ListItem Text="Under Review" value="1" />
                <asp:ListItem Text="Approved" value="2" /> 
                <asp:ListItem Text="Rejected" value="3" /> 
                <asp:ListItem Text="Logged" value="4" /> 
                <asp:ListItem Text="Completed" value="5" /> 
               </asp:DropDownList>
               }
               %>

这可能吗?如果是这样,我将如何根据userName显示不同的ListItem? 谢谢!

2 个答案:

答案 0 :(得分:5)

不要声明多个下拉列表。

相反,在代码隐藏中填充下拉列表:

if (username == "jpublic")
   ddlChangeStatus.DataSource = ...;
else
   ddlChangeStatus.DataSource = ...;

ddlChangeStatus.DataTextField = ...;
ddlChangeStatus.DataValueField = ...;
ddlChangeStatus.DataBind();

或者使用“静态”数据:

ddlChangeStatus.Items.Add(new ListItem("Under Review", "1"));
if (username != "jpublic")
{
   ddlChangeStatus.Items.Add(new ListItem("Approved", "2"));
   ddlChangeStatus.Items.Add(new ListItem("Rejected", "3"));
   ddlChangeStatus.Items.Add(new ListItem("Logged", "4"));
   ddlChangeStatus.Items.Add(new ListItem("Completed", "5"));
}

答案 1 :(得分:2)

您需要打开/关闭每个c#行。

<asp:DropDownList class="form-control" runat="server" AutoPostBack="true" ID="ddlChangeStatus">
<% if (userName == "jpublic"){ %>
            <asp:ListItem Text="Under Review" value="1" />
<% } else { %>
            <asp:ListItem Text="Under Review" value="1" />
            <asp:ListItem Text="Approved" value="2" /> 
            <asp:ListItem Text="Rejected" value="3" /> 
            <asp:ListItem Text="Logged" value="4" /> 
            <asp:ListItem Text="Completed" value="5" /> 
<% } %>
</asp:DropDownList>