简体   繁体   English

创建一个下拉列表C#MVC3

[英]Creating a dropdownlist c# mvc3

I am implementing a backoffice in mvc3 c# and i would like to have a field that is a drop down list with 3 fields "ComingSoon,Out,Showing". 我正在mvc3 c#中实现一个后台,我希望有一个字段是一个包含3个字段“ ComingSoon,Out,Showing”的下拉列表。 These fields are not a part of any class. 这些字段不是任何类的一部分。 Do i have to create a helper class ? 我是否需要创建一个助手类? i have tried the following 我尝试了以下

<% List<string> foo = new List<string>();
   foo.Add("Showing");
   foo.Add("ComingSoon);"
   foo.Add("Out");

   Html.DropDownList(foo, Model.Status); %>

Status is the field in the db that need to be updated. 状态是数据库中需要更新的字段。

Html.DropDownList("Status", 
    new SelectListItem[]{ new SelectListItem{ Text= "Showing", Value="Showing"},
    //same for others
}); 

Since you're using model binding, I'd suggest: 由于您使用的是模型绑定,因此建议:

<%: Html.DropDownListFor(model=> model.Status, 
                         new List<SelectListItem>() { 
                                new SelectListItem{ Text= "Showing", Value="Showing"},
                                new SelectListItem{ Text= "ComingSoon", Value="ComingSoon"},
                                new SelectListItem{ Text= "Out", Value="Out"}
                         }); %>

For modelbinding, always use the ones with 'For' at the end, it makes the Post-method easier + you get feedback if the name does not exist. 对于模型绑定,始终在末尾使用“ For”,这样可以简化后方法+如果名称不存在,您会得到反馈。

You can create dropdownlist this way. 您可以通过这种方式创建下拉列表。

@{          
    List<KeyValuePair<int, string>> dropdownList =
                                                        new List<KeyValuePair<int, string>>();
                dropdownList.Add(new KeyValuePair<int, string>(0,"Showing"));
                dropdownList.Add(new KeyValuePair<int, string>(1,"ComingSoon"));
                dropdownList.Add(new KeyValuePair<int, string>(2,"Out"));
                SelectList selectList = new SelectList(dropdownList, "key", "value", 0);

}

@Html.DropDownList("foo", selectList)

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

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