更改为使用 ViewModel 后 MVC3 ModelState 失败
我已更改控制器以传递 VoucherBatchViewModel 而不是 VoucherBatch
[HttpPost]
public ActionResult Edit(Guid id, VoucherBatchViewModel voucherBatchViewModel)
{
if (!ModelState.IsValid)
{
SetupDropDowns();
并且虚拟机:
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();
网页:
<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>
I've changed my controller to pass a VoucherBatchViewModel instead of a VoucherBatch
[HttpPost]
public ActionResult Edit(Guid id, VoucherBatchViewModel voucherBatchViewModel)
{
if (!ModelState.IsValid)
{
SetupDropDowns();
And the vm:
public class VoucherBatchViewModel
{
public VoucherBatch VoucherBatchInVM { get; set; }
public string CreationReference { get; set; }
public int NumberToMove { get; set; }
public int VoucherCodeLength { get; set; }
}
Question: Why is my ModelState invalid? The drop down has not populated the correct field in the ViewModel. The html does produce the correct
<div class="editor-field">
@Html.DropDownList("VoucherProviderId",
new SelectList(ViewBag.VoucherProviders as System.Collections.IEnumerable,
"Id", "Name", Model.VoucherBatchInVM.VoucherProviderId))
and Edit get contains this which I use to populate the 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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的
VoucherBatchViewModel
中看不到任何VoucherProviderId
属性。所以你的 HTML 无效。它应该是:为了实现这个标记,我建议你使用强类型助手:
并且请用强类型模型属性替换这个让我呕吐的
ViewBag
:Can't see any
VoucherProviderId
property in yourVoucherBatchViewModel
. So your HTML is not valid. It should be:And to achieve this markup you I would recommend you using strongly typed helpers:
And please replace this
ViewBag
which is making me vomit with a strongly typed model property: