11
我遇到一个问题,每次我发布表单回到控制器动作的[HttpPost]
版本时,ModelBinder都会返回一个空对象。我无法弄清楚为什么。如果我将签名更改为使用FormCollection
,则可以看到所有正确的密钥都已设置。有人能帮我指出这里有什么问题,因为我无法发现它。ASP.NET MVC Model Binder返回空对象
这里是模型我的看法
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> }
工作感谢!但为什么名称模型适用于另一个接受HttpPost数据的控制器? – Chris
该动作的模型是否也有一个名为Model的属性?它在这里失败的原因是因为名称冲突。 – counsellorben
对不起,我实际上误解了你之前说的,但我现在清楚了。感谢您的帮助。 – Chris