使用强类型 HTML 帮助程序进行 POST 时的 ASP MVC2 模型绑定问题
因此,我正在考虑从 MVC 1.0 迁移到 MVC 2.0 RTM。我想要开始遵循的约定之一是使用强类型 HTML 帮助程序来生成文本框等控件。
然而,看起来这并不是一件容易的事。我尝试迁移我的第一个表单,替换这样的行:
<%= Html.TextBox("FirstName", Model.Data.FirstName, new {maxlength = 30}) %>
...对于这样的行:
<%= Html.TextBoxFor(x => x.Data.FirstName, new {maxlength = 30}) %>
以前,这将使用以下方法签名映射到 POST 上适当的视图模型:
[HttpPost]
public ActionResult Registration(AccountViewInfo viewInfo)
相反,它当前会返回一个空对象。我相信这种脱节在于我们将视图模型传递到一个更大的聚合对象中,该对象具有一些页面元数据和其他有趣的东西(因此 x.Data.FirstName
而不是 x.FirstName)
。
所以我的问题是:使用强类型助手的最佳方法是什么,同时仍然允许 MVC 框架将表单集合适当地转换为我的视图模型,就像在原始行中那样?有没有什么方法可以在不改变我们传递给视图的聚合类型的情况下做到这一点?
谢谢!
更新:所以绑定属性运行良好,但我不喜欢如何将它应用到基本上每个发布的视图模型。我最终更改了继承层次结构,以便我们的所有视图模型都从包含页面内容和其他元数据的基类继承,而不是名为 Data
的聚合属性。
So I'm looking at moving from MVC 1.0 to MVC 2.0 RTM. One of the conventions I'd like to start following is using the strongly-typed HTML helpers for generating controls like text boxes.
However, it looks like it won't be an easy jump. I tried migrating my first form, replacing lines like this:
<%= Html.TextBox("FirstName", Model.Data.FirstName, new {maxlength = 30}) %>
...for lines like this:
<%= Html.TextBoxFor(x => x.Data.FirstName, new {maxlength = 30}) %>
Previously, this would map into its appropriate view model on a POST, using the following method signature:
[HttpPost]
public ActionResult Registration(AccountViewInfo viewInfo)
Instead, it currently gets an empty object back. I believe the disconnect is in the fact that we pass the view model into a larger aggregate object that has some page metadata and other fun stuff along with it (hence x.Data.FirstName
instead of x.FirstName)
.
So my question is: what is the best way to use the strongly-typed helpers while still allowing the MVC framework to appropriately cast the form collection to my view-model as it does in the original line? Is there any way to do it without changing the aggregate type we pass to the view?
Thanks!
UPDATE: So the bind attribute worked well, but I didn't love how I had to apply it to essentially every posted view model. I ended up changing the inheritance hierarchy such that all of our view models inherit from a base class that contains page content and other meta data, as opposed to being an aggregate property named Data
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这告诉绑定器它应该期望所有值都以 data 开头,因此它将查找 data.FirstName 等。
This tells the binder that it should expect all values to start with data, so it will look for data.FirstName, etc.