ASP.NET MVC 3:编程方式添加DataAnnotation(RequiredAttribute标签)来查看模型 [英] ASP.NET MVC 3: programmatically add DataAnnotation (RequiredAttribute) to view model

查看:153
本文介绍了ASP.NET MVC 3:编程方式添加DataAnnotation(RequiredAttribute标签)来查看模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用javascript不显眼的验证。我有我重新使用几种形式的图模型,并且在某些的形式,需要在视图模型的一些特性。在其他形式的,他们不应该。有没有一种方法以编程方式设置[必填]上的属性,这样我就可以做到这一点?

I am using javascript unobtrusive validation. I have a view model that I am re-using for several forms, and in some of the forms, some properties on the view model are required. On other forms they shouldn't be. Is there a way to programmatically set [Required] on properties, so that I can accomplish this?

谢谢!

推荐答案

无法使用DataAnnotations因为这些在编译时执行,并且不能动态地添加来完成。您可以

Cannot be done using DataAnnotations as these are implemented at compile time and cannot be added dynamically. You can either

创建具有适当注解不同的视图模型

Create different View Models that have the proper annotations

有您发送的视图模型的服务,它检查的基础上,它是从哪里来的,并返回验证错误的列表,你可以添加到您的模型状态的操作模式

Have a service that you send the view model to that checks the model based on the action that it is coming from and return a list of validation errors that you can append to your model state

戴上视图模型的属性,如字符串IsBeingUsedFor 和使用,在结合一个RequiredIf DataAnnotation。 这里是一个图书馆的例子已经建立使用条件DataAnnotations 的。然后,你可以说,[RequireIf(IsBeingUsedFor,Action_A)]

Put a property on the ViewModel such as string IsBeingUsedFor and use that in combination with a RequiredIf DataAnnotation. Here is an example of a library already build that uses conditional DataAnnotations. Then you can say, [RequireIf("IsBeingUsedFor", "Action_A")]

这些不一定所有的选项,但有些在吸尘器的几种。你可以做这一切在JavaScript中,但会丢失的服务器端验证,并可能在你的应用程序中打开了一些漏洞,如果一个'坏人'提交表单并绕过客户端验证。

These aren't necessarily all of the options, but the some of the cleaner ones. You could do this all in JavaScript, but you will lose server side validation and could open up some holes in your application if a 'bad person' submits the form and bypasses client side validation.

这篇关于ASP.NET MVC 3:编程方式添加DataAnnotation(RequiredAttribute标签)来查看模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆