如何禁用MVC的视野验证?视野、MVC

2023-09-03 06:23:52 作者:举杯畅饮诉情衷

我有一个MVC 3应用程序。 我有一个名为的usermodel模型,其中包含电子邮件字段,验证了独特的具有RemoteAttribute。我想使用的usermodel 2视图 - EditUser和CREATEUSER。我怎么能允许电子邮件现场验证的EditUser视图(因为这个领域是只读),并把它留在CREATEUSER看法?

I have an MVC 3 application. I have a model called UserModel that contains an email field, validated for unique with RemoteAttribute. I want to use UserModel on 2 Views - EditUser and CreateUser. How can I permit validation of email field on EditUser view(because there this field is readonly), and leave it on CreateUser view?

推荐答案

您可以使用部分验证技术来修改验证结果。这个例子将放弃对电子邮件字段的任何错误。

You can use the partial validation technique to modify the validation results. This example will discard any errors for the Email field.

public class DontValidateEmailAttribute : ActionFilterAttribute {

  public override void OnActionExecuting(ActionExecutingContext filterContext) {
    var modelState = filterContext.Controller.ViewData.ModelState; 
    var incomingValues = filterContext.Controller.ValueProvider;

    var key = modelState.Keys.Single(x => incomingValues.Equals("Email"));    
    modelState[key].Errors.Clear();

  }
}

和应用此属性的编辑器。

and apply this attribute to your Edit Controller.

我学到史蒂夫·桑德森的临ASP NET MVC 3 这种技术。他使​​用该技术来验证已要求领域的典范,但数据录入是一个多步骤向导。如果值尚未在形式返回后,他消除了错误,该属性。

I learnt this technique from Steve Sanderson's Pro ASP NET MVC 3. He uses the technique to validate a model that has required fields but the data entry is a multistep wizard. If the value has not been returned in the form post, he removes the errors for that property.