C# 没有类型为';IEnumerable<;选择列表项>';那有钥匙';职业';
我必须将选择列表添加到注册页面。我想在数据库中保存所选项目。我有这样的想法:C# 没有类型为';IEnumerable<;选择列表项>';那有钥匙';职业';,c#,asp.net-mvc-2,drop-down-menu,C#,Asp.net Mvc 2,Drop Down Menu,我必须将选择列表添加到注册页面。我想在数据库中保存所选项目。我有这样的想法: <%: Html.DropDownListFor(m => m.Profession, new SelectList(new string[] {"Prof1", "Prof2", "Prof3", "Prof4", "Prof5"}, "Prof1"))%> <%: Html.ValidationMessageFor(m => m.Profession)%
<%: Html.DropDownListFor(m => m.Profession, new SelectList(new string[] {"Prof1", "Prof2", "Prof3", "Prof4", "Prof5"}, "Prof1"))%>
<%: Html.ValidationMessageFor(m => m.Profession)%>
在查看页面中:
<%: Html.DropDownListFor(m => m.Profession, (IEnumerable<SelectListItem>)ViewData["ProfessionList"])%>
<%: Html.ValidationMessageFor(m => m.Profession)%>
在控制器中:
ViewData["ProfessionList"] =
new SelectList(new[] { "Prof1", "Prof2", "Prof3", "Prof4", "Prof5"}
.Select(x => new { value = x, text = x }),
"value", "text");
public ActionResult Index()
{
var professions = new[] { "Prof1", "Prof2", "Prof3", "Prof4", "Prof5" }
.Select(x => new SelectListItem { Value = x, Text = x });
var model = new MyViewModel
{
ProfessionList = new SelectList(professions, "Value", "Text")
};
return View(model);
}
我得到了一个错误:没有类型为“IEnumerable”的ViewData项具有键“Profession”
我该怎么做才能使它工作?我建议使用视图模型而不是ViewData。因此:
public class MyViewModel
{
[Required]
[DisplayName("Profession")]
public string Profession { get; set; }
public IEnumerable<SelectListItem> ProfessionList { get; set; }
}
在你看来:
<%: Html.DropDownListFor(m => m.Profession, Model.ProfessionList) %>
<%: Html.ValidationMessageFor(m => m.Profession) %>
m.Profession,Model.ProfessionList)%>
m、 职业)%>
您可以在视图中定义SelectList,如下所示:
<%: Html.DropDownListFor(m => m.Profession, new SelectList(new string[] {"Prof1", "Prof2", "Prof3", "Prof4", "Prof5"}, "Prof1"))%>
<%: Html.ValidationMessageFor(m => m.Profession)%>
m.Profession,新选择列表(新字符串[]{“Prof1”、“Prof2”、“Prof3”、“Prof4”、“Prof5”},“Prof1”))%>
m、 职业)%>
在“选择列表”中强制转换,为什么要在IEnumerable中强制转换??DropDownListFor方法接受selectList。我在“selectList”中强制转换它,但得到相同的错误。我认为它是可数的,这就是我使用它的原因。