【问题标题】:How to use ASP.NET tag in a server control?如何在服务器控件中使用 ASP.NET 标记?
【发布时间】:2013-07-18 17:30:32
【问题描述】:

我有一个下拉菜单

 <div>
     <asp:DropDownList ID="RegistrationDropDownList" runat="server">
         <asp:ListItem Value="NULL">All records</asp:ListItem>
         <asp:ListItem Value="1">Submitted records</asp:ListItem>
         <asp:ListItem Value="0">Non-Submitted records</asp:ListItem>
     </asp:DropDownList>
 </div>

我想根据会话变量显示/隐藏&lt;asp:ListItem Value="NULL"&gt;All records&lt;/asp:ListItem&gt;

所以我就这样尝试了

 <asp:DropDownList ID="RegistrationDropDownList" runat="server">
 <%if (Convert.ToInt32(Session["user_level"]) == 1){ %>
     <asp:ListItem Value="NULL">All records</asp:ListItem>
 <%}%>
     <asp:ListItem Value="1">Submitted records</asp:ListItem>
     <asp:ListItem Value="0">Non-Submitted records</asp:ListItem>
 </asp:DropDownList>

但是我遇到了一个错误

此上下文不支持代码块

我知道我不能在具有 runat="server" 的控件上使用代码块,但删除它会破坏我的逻辑代码。

我该如何解决这个问题?

【问题讨论】:

  • 你能告诉我们逻辑背后的代码吗?
  • 听起来条件应该在代码隐藏而不是控制标记中。也许在Page_Load 中,您可以检查条件并从DropDownList 中删除NULL 值项。 (或相反,检查相反的条件以添加NULL 值。)
  • 你为什么不在后面的代码中构建列表?
  • 当您将 runat='server' 添加到 HTML 控件时,您会更改渲染,并且内部不支持代码块。

标签: asp.net drop-down-menu webforms


【解决方案1】:

这应该在后面的代码中完成:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack && Convert.ToInt32(Session["user_level"]) == 1)
    {
        RegistrationDropDownList.Items.Insert(0, new ListItem("All records", "NULL"));
    }
}

【讨论】:

  • 废话 2 分钟干得好
  • 谢谢解决了我的问题,你知道为什么加载后默认为第二个列表项(提交记录)
【解决方案2】:

在后面的代码中添加

if (Convert.ToInt32(Session["user_level"]) == 1)
            {
                ListItem newItem = new ListItem();
                newItem.Value = null;
                newItem.Text = "All record";
                DropDownList1.Items.Add(newItem);

            }

【讨论】:

    【解决方案3】:

    很遗憾ListItem 没有可以绑定的Visibility 属性。我能想到的最好的解决方案是写一个扩展DropDownList的类;添加一个在渲染之前插入“所有记录”项的方法。

    public class ExtendedList : DropDownList
    {
        protected override void OnLoad(EventArgs e)
        {
            if (Convert.ToInt32(Session["user_level"]) == 1)
            {
                Items.Insert(0, new ListItem { Value = "NULL", Text = "All Records" });
            }
        }
    }
    

    【讨论】:

    • Items.Add 将添加为最后一项,而不是使用 Insert 将其添加到位置 0
    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 2011-03-09
    • 2012-01-22
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    • 2012-07-12
    • 2011-01-01
    相关资源
    最近更新 更多