我遇到一个问题,每当我将表单发布回控制器操作的[HttpPost]
版本时,ModelBinder都会返回一个null对象。我无法理解为什么。如果我更改签名以使用FormCollection
,我可以看到已设置所有正确的密钥。有人可以帮我指出这里有什么问题,因为我无法发现它。
以下是处理我的观点的模型
public class DeviceModel
{
public int Id { get; set; }
[Required]
[Display(Name = "Manufacturer")]
public int ManufacturerId { get; set; }
[Required]
[Display(Name = "Model")]
[StringLength(20)]
public string Model { get; set; }
[StringLength(50)]
[Display(Name = "Name")]
public string Name { get; set; }
[StringLength(50)]
[Display(Name = "CodeName")]
public string CodeName { get; set; }
public int? ImageId { get; set; }
}
public class DeviceCreateViewModel : DeviceModel
{
public IEnumerable<SelectListItem> Manufacturers { get; set; }
}
我在控制器中使用的是这样的:
public ActionResult Create()
{
DeviceCreateViewModel viewModel = new DeviceCreateViewModel()
{
Manufacturers = ManufacturerHelper.GetSortedManufacturersDropDownList()
};
return View(viewModel);
}
[HttpPost]
public ActionResult Create(DeviceModel model)
{
// if I check model here it is NULL
return View();
}
视图如下:
@model TMDM.Models.DeviceCreateViewModel
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
@Html.LabelFor(model => model.ManufacturerId)
</div>
<div class="editor-field">
@Html.DropDownList("ManufacturerId", Model.Manufacturers)
@Html.ValidationMessageFor(model => model.ManufacturerId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Model)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Model)
@Html.ValidationMessageFor(model => model.Model)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.CodeName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.CodeName)
@Html.ValidationMessageFor(model => model.CodeName)
</div>
<p>
<input type="submit" value="Save" class="medium green awesome" />
@Html.ActionLink("Cancel", "Index", "Device", null, new { @class="medium black awesome" })
</p>
</fieldset> }
答案 0 :(得分:29)
问题是类Model
中名为DeviceModel
的属性与model
操作中名为Create
的变量之间存在名称冲突。名称冲突导致DefaultModelBinder
失败,因为它尝试将Model属性绑定到DeviceModel类。
将“创建”操作中的变量名称更改为deviceModel
,它将正确绑定。