ASP.NET MVC 2 动态生成模型中的数据注释
我正在创建一个 asp.net mvc 2 应用程序,根据用户输入动态生成视图模型。简而言之,用户可以选择他想在视图中看到哪些字段。
由于模板化助手严重依赖于模型属性和属性(数据注释),因此我需要在运行时以某种方式将属性添加到视图模型中。不用说,这不是一个简单的任务。
那么,在这种情况下,你们建议我做什么?我无法静态添加属性,所以我应该继续尝试动态添加它们,即使这需要大量工作,还是应该尝试使用不同的方法?
提前致谢!
费利佩
I am creating an asp.net mvc 2 application generating my view model dynamically depending on user input. Simply put, the user is able to choose which fields he wants to see in his View.
Since the templated helpers rely heavily on model properties and attributes (data annotations), I would need to somehow add the attributes to the view model during runtime. No need to say that this is not a simple task.
So, what do you guys recommend me to do in this scenario? I'm not able to add the attributes statically, so should I go ahead and try to add them dynamically even if it is a lot of work or should I try to use a different approach?
Thanks in advance!
Felipe
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
自定义模型绑定器只会在绑定部分为您提供帮助。它对 ASP.NET MVC 的模板化助手或其他功能没有帮助。
我建议编写一个自定义元数据提供程序,而不是继承ModelMetadataProvider 并使用 ModelMetadataProviders。自定义元数据提供程序可以从任何需要的地方获取其元数据:CLR 属性、XML 文件、数据库或随机数生成器。内置数据注释提供程序当然使用 CLR 属性。
您可能需要查看内置数据注释元数据提供程序的源代码,以了解如何实现提供程序的示例。您可以从 CodePlex 站点 下载 ASP.NET MVC 2 RC 2 源代码。 MVC Futures 项目中也可能有一个实现,但我不确定。
A custom model binder would only help you in the binding part. It won't help with the templated helpers or other features of ASP.NET MVC.
I recommend writing a custom metadata provider instead by inheriting from ModelMetadataProvider and registering your provider in global.asax by using ModelMetadataProviders. A custom metadata provider can get its metadata from anywhere it wants: CLR attributes, XML file, database, or a random number generator. The built-in Data Annotations provider of course uses CLR attributes.
You might want to take a look at the source code for the built-in Data Annotations metadata provider to see an example of how to implement a provider. You can download the ASP.NET MVC 2 RC 2 source code from the CodePlex site. There might also be an implementation in the MVC Futures project, but I'm not sure.
似乎您需要一个动态应用验证的自定义视图模型绑定器。
Seems like you would need a custom view model binder that applies validation dynamically.
听起来有点矫枉过正(如果我理解正确的话)——那就是动态创建模型。您没有利用模型的主要好处;编译时间检查。
我会尝试使用特定于任务的对象(例如,具有 UserFormFields 类列表等的 UserForm 类),而不是动态创建它们。
编辑:我的建议是不要使用基于属性的验证并在设计模型时考虑到验证。像下面这样的设计可能会更好地解释我的观点:
Sounds like overkill (if I understand correctly) - that is creating models on the fly. You are not using the main benefit of having models; compile time checks.
I'd try to use objects specific to the task (for example a UserForm class which would have List of UserFormFields classes and so on) in hand and not create them on the fly.
Edit: What I am suggesting is to not use attribute based validation and design your model with validation in mind. A design like below might explain my point better: