我在POST表单时遇到上述错误,我认为遭遇错误的根本原因是“DropDownListFor”,其中复数SelectList两次调用,如果是,请建议解决方案?
如果我从“x => x.Values”更改为“x => x.Name”,则还会收到错误“没有类型'IEnumerable'的ViewData项具有键'DDLView.Name' 。“
编辑模板
@model DropDownListViewModel
@Html.LabelFor(x=>x.Values, Model.Label)
@Html.DropDownListFor(x=>x.Values, Model.Values)
查看模型
public class HomePageViewModel
{
public DropDownListViewModel DDLView { get; set; }
}
public class DropDownListViewModel
{
public string Label { get; set; }
public string Name { get; set; }
public SelectList Values { get; set; }
}
控制器
public ActionResult Index()
{
HomePageViewModel homePageViewModel = new HomePageViewModel();
homePageViewModel.DDLView = new DropDownListViewModel
{
Label = "drop label1",
Name = "DropDown1",
Values = new SelectList(
new[]
{
new {Value = "1", Text = "text 1"},
new {Value = "2", Text = "text 2"},
new {Value = "3", Text = "text 3"},
}, "Value", "Text", "2"
)
};
}
[HttpPost]
public ActionResult Index(HomePageViewModel model)
{
return View(model);
}
查看
@model Dynamic.ViewModels.HomePageViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x=>x.DDLView)
<input type="submit" value="OK" />
}
答案 0 :(得分:3)
问题是SelectList没有无参数构造函数,模型绑定器无法实例化它,但是你试图将其发回。
要解决您的问题,请更改实施中的两件事:
1)更改编辑器模板
@Html.DropDownListFor(x=>x.Values, Model.Values)
到
@Html.DropDownListFor(x=>x.ValueId, Model.Values)
2)在你的原始DropDownListViewModel
旁边添加[ScaffoldColumn(false)]
public string ValueId { get; set; }
现在,您的帖子操作参数将填充正确的值。