简体   繁体   English

显示下拉列表

[英]Display DropDownList

I am trying to build a drop down list using enum . 我正在尝试使用enum建立一个下拉列表。 I tried the following, but do not know how to display it in view. 我尝试了以下操作,但不知道如何在视图中显示它。 I am using MVC framework 我正在使用MVC framework

 public enum Condition
        {
            And,
            Or,
            Not,
        }

 private List<Condition> userTypes = Enum.GetValues(typeof(Condition)).Cast<Condition>().ToList();

       public List<Condition> UserType
       {
           get
           {
               return userTypes;
           }
           set
           {
               userTypes = value;
           }
       }

Is the above code right to display a simple drop down list? 上面的代码显示一个简单的下拉列表是否正确? And how do I pass in it view to display drop down list. 以及如何传递视图以显示下拉列表。 Thanks 谢谢

in your Action : 在您的Action

ViewData["ddl"] = userTypes.Select(t => new SelectListItem { Text = t.ToString(), Value = ((int)t).ToString() });

in your aspx : 在您的aspx

<%=Html.DropDownList("ddl", ViewData["ddl"] as IEnumerable<SelectListItem>)%>

Rest of this is alright. 其余的一切都很好。

You suppose to return string list from property UserType not Condition type. 您假设从属性UserType而不是Condition类型返回string列表。 Secondly property must is of readonly since enum is constant and user won`t going to change it. 其次,属性必须是readonly因为枚举是恒定的,用户不会更改它。 Lastly don't use variable, property itself handle this. 最后,不要使用变量,属性本身可以处理此问题。

public List<string> UserType
{
   get
   {
      return Enum.GetNames(typeof(Condition)).ToList();
   }
}
  1. In your model add a List like: 在模型中添加一个类似于以下内容的列表:

    \n private List conditionList= Enum.GetValues(typeof(Condition)) 私有列表conditionList = Enum.GetValues(typeof(Condition))\n                    .Cast() 。投()\n                    .Select(e => new SelectListItem { Value = ((int)e).ToString(), Text = e.ToString() }); .Select(e => new SelectListItem {值=((int)e).ToString(),文本= e.ToString()}); \n
  2. And Then just add this on your view 然后将其添加到您的视图中

    \n@Html.EditorFor(m=>m.Condition,Model.conditionList) @ Html.EditorFor(M => m.Condition,Model.conditionList)    \n

I believe that will make things more easier. 我相信这会使事情变得更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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