MVC 3 模型绑定到半个长桌
我正在尝试绑定到一个相当大的 SQL 数据库表,其中包含 100 多个字段。我正在进行基本的 CRUD 操作,当涉及到编辑时,我决定将编辑分成两个页面(视图),只是为了保持页面长度易于管理且用户友好。我使用 MVC 3 (C#) 和实体框架来映射数据库。
我的问题 - 如何在每个 ActionResult 中绑定到该表的“一半”?有两个问题 - 我正在使用分部类和 MetadataType 属性验证大多数输入。如何拆分验证,以便一个页面不会验证另一页面的字段?其次,如何只绑定表的一半属性?许多都是不可为空的,如果它们尝试在没有相应表单输入的情况下进行绑定,则会触发数据库错误。
我知道我可以在我的两个 ActionResults 中使用 [Bind(Include="...")] 或 [Bind(Exclude="...")],但在其中列出 50 个单独的字段似乎非常不合逻辑且不干。包含或排除标签。有更好的方法吗?
I am trying to bind to a rather large SQL database table with over 100 fields. I'm doing basic CRUD operations, and when it comes to editing, I've decided to split up the editing into two pages (Views), just to keep the page lengths manageable and user-friendly. I'm using MVC 3 (C#) with the Entity Framework to map the database.
My question - how do I bind to "half" of this table in each ActionResult? There are two issues - I am validating most of the inputs using a partial class and the MetadataType attribute. How do I split up the validations so that one page is not validating fields for the other? Secondly, how do I bind to only half of the properties of the table? Many are non-nullable and would trigger database errors if they attempted to bind without corresponding form inputs.
I know I could use [Bind(Include="...")] or [Bind(Exclude="...")] in my two ActionResults, but it seems pretty illogical and non-DRY to list 50 individual fields in an include or exclude tag. Is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
嗯,你有很多选择。首先,您将需要特定于您的视图的专用视图模型。必须在不同的模型中复制这些属性似乎违反了 DRY,但现实是视图模型和数据模型有两个目的,因此是不同的关注点。你需要将它们分开。
您只需将在视图中使用的属性放置在每个视图的视图模型中。
其次,如果您的数据模型不利于逐步更新,那么您将必须将每个视图的数据存储在某个地方,以便您可以进行单次更新。
您可以将其存储在临时表中,也可以序列化数据并将其存储在视图中的隐藏字段中。 MVC Futures 项目提供了一个方便的 Serialize html 帮助器来帮助解决这个问题。无论哪种方式,您都需要将事情分解,以便可以进行部分编辑。
Well, you have a number of options. First, you're going to need dedicated View Models that are specific to your views. It may seem to violate DRY to have to duplicate these properties in different models, but the reality is that View Models and Data Models serve two purposes, and thus are different concerns. You need to keep them seperate.
You would only place the properties you're using in the view in the View Model for each View.
Second, if your data model is not conducive to gradual updates, then you will have to store the data from each view somewhere so that you can do a single update.
You could store it in a temporary table, or you could serialize the data and store it in a hidden field in the view. The MVC Futures project provides a handy Serialize html helper that will help with that. Either way, you will need to break things up so that you can do a partial edit.
我想我可能误解了这一点...经过测试,看起来 MVC 模型绑定毕竟允许部分绑定。
I think I may have misunderstood this... after testing it looks like the MVC model binding allows for partial binding after all.