ASP.NET MVC - Comprehensive Model Validation

I have a ViewModel class, for example:

class CaseModel {
    public Boolean     ClientPresent { get; set; }
    public ClientModel Client        { get; set; }
}

class ClientModel {
    [Required]
    public String      FirstName     { get; set; }
    [Required]
    public String      LastName      { get; set; }
}

The browse page consists of a partial view <input type="checkbox" name="ClientPresent" />and Html.EditorFor( m => m.Client ).

The idea is that when the user, providing information about the case (object of a business domain), can choose not to specify any information about the client (another object-object), unchecking the ClientPresent box.

, ASP.NET MVC ClientModel, CaseModel.Client , , FirstName LastName aren ' t (), , , [Required], ViewData.ModelState.IsValid false, .

, CaseModel.Client , CaseModel.ClientPresent - false?

, ClientModel ViewModel (, ClientController, ).

+5
2

, , : , , , , , , .

, , . - , :

public class CaseModel {
    public void CleanValidation(ModelStateDictionary dict) {
        if( this.ClientPresent ) {
            dict.Keys.All( k => if( k.StartsWith("Client") dict[k].Errors.Clear() );
        }
    }
}

(, , )

CleanValidation :

public void Edit(Int64 id, CaseModel model) {
    model.CleanValidation( this.ModelState );
}

, , , CleanValidation IComplexModel, , .

:

, ViewModel, :

public interface ICustomValidation {

    void Validate(ModelStateDictionary dict);
}

CaseModel :

 public class CaseClientModel : ICustomValidation {

      public Boolean ClientIsNew { get; set; } // bound to a radio-button
      public ClientModel ExistingClient { get; set; } // a complex viewmodel used by a partial view
      public ClientModel NewClient { get; set; } // ditto

      public void Validate(ModelStateDictionary dict) {

          // RemoveElementsWithPrefix is an extension method that removes all key/value pairs from a dictionary if the key has the specified prefix.
          if( this.ClientIsNew ) dict.RemoveElementsWithPrefix("ExistingClient");
          else                   dict.RemoveElementsWithPrefix("NewClient");
      }
 }

BaseController OnActionExecuting:

protected override void OnActionExecuting(ActionExecutingContext filterContext) {
    base.OnActionExecuting(filterContext);
    if( filterContext.ActionParameters.ContainsKey("model") ) {

        Object                    model = filterContext.ActionParameters["model"];
        ModelStateDictionary modelState = filterContext.Controller.ViewData.ModelState; // ViewData.Model always returns null at this point, so do this to get the ModelState.

        ICustomValidation modelValidation = model as ICustomValidation;
        if( modelValidation != null ) {
            modelValidation.Validate( modelState );
        }
    }
}
+3

.

  public class CustomModelBinder: DefaultModelBinder
  {
    protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
    {
      if (propertyDescriptor.Name == "Client")
      {
          var clientPresent = bindingContext.ValueProvider.GetValue("ClientPresent");

          if (clientPresent == null || 
                string.IsNullOrEmpty(clientPresent.AttemptedValue))
              return;
      }

      base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
    }
  }

Global.asax.cs

ModelBinders.Binders.Add(typeof(CaseModel), new CustomModelBinder());
+2

All Articles