我必须添加选择列表到注册页面。并且我想要在数据库中保存选定的项目。我有类似的东西:
在查看页面中:
<%: Html.DropDownListFor(m => m.Profession, (IEnumerable<SelectListItem>)ViewData["ProfessionList"])%>
<%: Html.ValidationMessageFor(m => m.Profession)%> 在模型类中:
[Required]
[DisplayName("Profession")]
public string Profession { get; set; } 在控制器中:
ViewData["ProfessionList"] =
new SelectList(new[] { "Prof1", "Prof2", "Prof3", "Prof4", "Prof5"}
.Select(x => new { value = x, text = x }),
"value", "text");我得到了一个错误:没有'IEnumerable‘类型的ViewData项的关键字是'Profession’。
我能做些什么来让它工作呢?
发布于 2011-03-10 03:06:45
您可以像这样在视图中定义SelectList:
<%: Html.DropDownListFor(m => m.Profession, new SelectList(new string[] {"Prof1", "Prof2", "Prof3", "Prof4", "Prof5"}, "Prof1"))%>
<%: Html.ValidationMessageFor(m => m.Profession)%>发布于 2011-03-10 01:42:28
我建议使用视图模型而不是ViewData。所以:
public class MyViewModel
{
[Required]
[DisplayName("Profession")]
public string Profession { get; set; }
public IEnumerable<SelectListItem> ProfessionList { get; set; }
}在你的控制器中:
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);
}在你看来:
<%: Html.DropDownListFor(m => m.Profession, Model.ProfessionList) %>
<%: Html.ValidationMessageFor(m => m.Profession) %>https://stackoverflow.com/questions/5245329
复制相似问题