我再次面临“这不应该是这样的?*!#hard”的情况。
问题:我想在 MVC 中使用表单来创建对象。对象的一个元素是一组有限的选择——下拉列表的完美候选者。
但是,如果我在我的模型中使用 SelectList,并在我的视图中使用下拉列表,然后尝试将模型发布回我的 Create 方法,我会收到错误“Missing Method Exception:No Parameterless constructor for this object”。探索 MVC 源代码,似乎为了绑定到模型,Binder 必须能够首先创建它,并且它无法创建 SelectList,因为它没有默认构造函数。
这是简化的代码:对于模型:
public class DemoCreateViewModel
{
public SelectList Choice { get; set; }
}
对于控制器:
//
// GET: /Demo/Create
public ActionResult Create()
{
DemoCreateViewModel data = new DemoCreateViewModel();
data.Choice = new SelectList(new string[] { "Choice1", "Choice2", "Choice3" });
ViewData.Model = data;
return View();
}
//
// POST: /Demo/Create
[HttpPost]
public ActionResult Create(DemoCreateViewModel form)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
对于视图:
<fieldset>
<legend>Fields</legend>
<%= Html.LabelFor(model => model.Choice) %>
<%= Html.DropDownListFor(model => model.Choice, Model.Choice) %>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
现在,我知道我可以通过后退 10 码并下注来完成这项工作:绕过模型绑定并返回到 FormCollection 并自己验证和绑定所有字段,但必须有一个更简单的方法。我的意思是,这是一个尽可能简单的要求。有没有办法在 MVC ModelBinding 架构中完成这项工作?如果是这样,它是什么?如果没有,怎么会?
编辑:嗯,我脸上有鸡蛋,但也许这对其他人有帮助。我做了一些更多的实验,并找到了一个似乎可行的简单解决方案。
提供一个简单值(字符串或整数,具体取决于您的选择列表值类型),并将其命名为您绑定到的模型元素。然后提供第二个元素作为选项的选择列表,并将其命名为其他名称。所以我的模型变成了:
public class DemoCreateViewModel
{
public string Choice { get; set; }
public SelectList Choices { get; set; }
}
然后View中的DropDownListFor语句就变成了:
<%= Html.DropDownListFor(model => model.Choice, Model.Choices) %>
当我这样做时,提交按钮正确地将表单中的选择绑定到字符串 Choice,并将模型提交回第二个 Create 方法。