Chr*_*ris 11 asp.net model-binding asp.net-mvc-3
我遇到一个问题,每次我将表单发回到[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; }
}
Run Code Online (Sandbox Code Playgroud)
我在我的控制器中使用的是这样的:
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();
}
Run Code Online (Sandbox Code Playgroud)
视图看起来像这样:
@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> }
Run Code Online (Sandbox Code Playgroud)
cou*_*ben 29
问题是Model类中命名的属性与操作中DeviceModel命名的变量之间存在名称冲突.名称冲突导致失败,因为它尝试将Model属性绑定到DeviceModel类.modelCreateDefaultModelBinder
将Create操作中的变量名称更改为deviceModel,它将正确绑定.
| 归档时间: |
|
| 查看次数: |
8716 次 |
| 最近记录: |