是否有可能切换验证数据注释开/关在MVC 3? [英] Is it possible to toggle Validation Data Annotations on/off in MVC 3?

查看:160
本文介绍了是否有可能切换验证数据注释开/关在MVC 3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个单独的视图访问相同的模型。当我把验证数据的注释在模型上,它可以作为发布和$ P $如果留空或不在范围内被提交(两个视图)pvents的数据。不过,我有一个观点,即应能允许而另一种观点认为需要要求将输入或选择它让它通过之前的信息空或空值被保存为属性。换句话说,我想在模型内关闭验证器的属性一个视图,并把它留在了另一种观点。这里的例子code:

I have two separate VIEWS accessing the same MODEL. When I put the validator data annotations on the model, it works as advertised and prevents the data from being submitted (for both views) if left blank or not within range. However, I have one view that should be able to allow empty or null values to be saved for a property whereas another view needs to require information to be entered or selected before it lets it through. In other words, I'd like to turn off the validator on the property within the MODEL for one view and leave it on for the other view. Here's the example code:

MODEL:

[Range(1, 999, ErrorMessage = "A submittal is required")]
public int SubmittalId { get; set; }

查看#1:

 <label>@Model.AuditDoc.SubmittalsLabel.ConfigurableLabelDesc</label> @Html.ValidationMessageFor(x => x.AuditDoc.SubmittalId) @Html.DropDownListFor(x => x.AuditDoc.SubmittalId, new SelectList(Model.AuditDoc.ListOfSubmittals, "Id", "Name"))

查看#2:

 <label>@Model.AuditDoc.SubmittalsLabel.ConfigurableLabelDesc</label> @Html.DropDownListFor(x => x.AuditDoc.SubmittalId, new SelectList(Model.AuditDoc.ListOfSubmittals, "Id", "Name"))

正如你可以看到,我想禁用浏览#2验证数据的注释,并把它打开,查看#1。

As you can see, I would like to disable that validator data annotation for View #2 and leave it on for View #1.

推荐答案

这是无法通过数据注解的缺省设置。但是,你必须使用两个独立的视图模型或编写自己的validationAttribute的选择。

This isn't possible via the default set of data annotations.. however, you have the choice of using 2 separate view models or writing your own validationAttribute.

我写这一次..虽然我讨厌使用它。

I wrote this once.. although I loathed using it..

public class RequiredOnAttribute : ValidationAttribute
{
    public string[] URLs { get; set; }

    public override bool IsValid(object value)
    {
        if (URLs.Contains(System.Web.HttpContext.Current.Request.Url.AbsolutePath))
        {
            if (string.IsNullOrEmpty(value as string))
            {
                return false;
            }
        }
        return true;
    }
}

用法:

[RequiredOn(URLs = new string[] { "/create", "/edit" })]
public string MyModelField { get; set; }

您可以为范围,正则表达式等做同样的..

You could do the same for Range, RegEx, etc..

这篇关于是否有可能切换验证数据注释开/关在MVC 3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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