更改为使用ViewModel后,MVC3 ModelState失败

时间:2011-04-06 05:04:20

标签: asp.net-mvc-3 viewmodel

我已将控制器更改为传递VoucherBatchViewModel而不是VoucherBatch

 [HttpPost]
    public ActionResult Edit(Guid id, VoucherBatchViewModel voucherBatchViewModel)
    {
        if (!ModelState.IsValid)
        {
            SetupDropDowns();

和vm:

 public class VoucherBatchViewModel
{
    public VoucherBatch VoucherBatchInVM { get; set; }
    public string CreationReference { get; set; }
    public int NumberToMove { get; set; }
    public int VoucherCodeLength { get; set; }
}

问题:为什么我的ModelState无效?下拉列表未填充ViewModel中的正确字段。 html确实产生了正确的

<div class="editor-field">
    @Html.DropDownList("VoucherProviderId",
            new SelectList(ViewBag.VoucherProviders as System.Collections.IEnumerable,
            "Id", "Name", Model.VoucherBatchInVM.VoucherProviderId))

和Edit get包含了我用来填充DropDown的内容。

 ViewBag.VoucherProviders = uow.VoucherProviders.OrderBy(v => v.Name).ToList();

HTML:

    <select id="VoucherProviderId" name="VoucherProviderId"><option value="0469f9ba-c4ea-401a-86f1-095208c6a7fb">Name</option>
<option selected="selected" value="e0aeed44-3574-46f1-a493-0a6a87948942">Voucher Provider 1</option>
<option value="5abe1158-282b-4330-9b11-01de503a2f16">Voucher Provider 2</option>

1 个答案:

答案 0 :(得分:0)

VoucherProviderId中看不到任何VoucherBatchViewModel属性。所以你的HTML无效。它应该是:

<select id="VoucherProviderId" name="VoucherBatchInVM.VoucherProviderId">
    ...
</select>

要实现此标记,我建议您使用强类型帮助程序:

@Html.DropDownListFor(
    x => x.VoucherBatchInVM.VoucherProviderId,
    new SelectList(ViewBag.VoucherProviders as System.Collections.IEnumerable, "Id", "Name")
)

请替换这个ViewBag,这会让我呕吐一个强类型的模型属性:

@Html.DropDownListFor(
    x => x.VoucherBatchInVM.VoucherProviderId,
    new SelectList(Model.VoucherProviders, "Id", "Name")
)