包含多个对象的 ViewModel 的模型绑定
我有一个 ProductListingViewModel 类型的强类型视图,它又包含一个 ProductViewModel。 (都是自定义视图模型)。
我的页面上有一些表单元素,它们的创建方式如下:
<%: Html.DropDownListFor(m => m.ProductViewModel.CategoryId, Model.Categories)%>
生成 HTML:
<select name="ProductViewModel.CategoryId" id="CategoryId">
使用默认模型绑定,我期望当我发布到接受 ProductListingViewModel 类型参数的控制器操作时,它会知道填充ProductViewModel.CategoryId 以及相关数据。
选择列表的名称似乎表明它知道有一个带有 CategoryId 属性的 ProductViewModel,但是当我发布到我的控制器方法时,ProductViewModel 为 null。如果我在构造 ProductListingViewModel 期间创建它,那么它不再为 null,但默认绑定器似乎没有按照我的预期填充属性。
这是自定义模型绑定器的情况还是我只是缺少一些基本的东西?
干杯。
I have a strongly typed view of type ProductListingViewModel which in turn contains a ProductViewModel. (both custom view models).
I have some form elements on my page and these are created like so:
<%: Html.DropDownListFor(m => m.ProductViewModel.CategoryId, Model.Categories)%>
which generates the HTML:
<select name="ProductViewModel.CategoryId" id="CategoryId">
With the default model binding I expected that when I post to my controller action which accepts a parameter of type ProductListingViewModel, that it'd know to populate the ProductViewModel.CategoryId with the relevant data.
The name of the select list seems to indicate that it knows there's a ProductViewModel with a CategoryId property however when I post to my controller method, the ProductViewModel is null. If I create this during construction of the ProductListingViewModel then it's no longer null but the default binder doesn't seem to be populating the properties as I expected.
Is this a case for a custom model binder or am I just missing something fundamental?
Cheers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我看来,默认的活页夹应该在这种情况下工作。
您是否尝试过使用 Fiddler 检查客户端发送的数据?
控制器操作的签名到底是什么?
It seems to me that the default binder should work in this case.
Did you try using Fiddler for checking the data sent from the client?
What exactly is the signature of the controller action?
让我尝试总结一下(如果我错了,请纠正我)。
模型:
控制器:
视图:
现在,当您提交表单时,您将得到:
这不是您想要的吗?
Let me try to summarize (correct me if I am wrong).
Model:
Controller:
View:
Now when you submit the form you will get:
Isn't what you are after?