Shivprasad Koirala
Shivprasad Koirala

Reputation: 28646

MVC data annotation validation is not firing when i use model binders

Note sure but i am looking stupid for this.I have created a simple model binder as shown below.

 public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            HttpRequestBase request = controllerContext.HttpContext.Request;
            Customer obj = (Customer)base
                    .BindModel(controllerContext, bindingContext);
            obj.CustomerName = request.Form["Text1"];
            return obj;

}

I have a required field validator on the Customer model

 public class Customer
    {
        private string _CustomerName;

        [Required]
        public string CustomerName
        {
            get { return _CustomerName; }
            set { _CustomerName = value; }
        }

    }

in Global.asax i have tied up the model with the binder

 ModelBinders.Binders.Add(typeof(Customer), new MyBinder());

But when i check the ModelState.IsValid its always false. What am i missing here ?

Upvotes: 2

Views: 205

Answers (1)

xDaevax
xDaevax

Reputation: 2022

By directly accessing the property, you're bypassing the data annotations binding invoked by the default model binder (which happens as part of BindModel method).

You'll either need to let the base handle this behavior by having the request item have the same name as your CustomerName property, or invoke it yourself: http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx

Here is a snippet from the above linked site (adapted for your code):

var cust = new Customer();
var context = new ValidationContext(cust, serviceProvider: null, items: request);
var results = new List<ValidationResult>();

var isValid = Validator.TryValidateObject(cust, context, results);

if (!isValid)
{
    foreach (var validationResult in results)
    {
        Console.WriteLine(validationResult.ErrorMessage);
    }
}

Upvotes: 1

Related Questions