2

I’m new to MVC.NET and can’t seem to understand why my validate function is not being called which sits inside of a MyModel class.

MyModel:

Public string Name { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
// validation logic which is not being called on post. 
}

When I post the form, I’m actually posting my ViewModel that has a property of MyModel.

ViewModel:

Public MyModel { get; set; }

Controller:

[HttpPost]
public ActionResult Index(ViewModel model)
{
    // this is always true??
    if(this.ModelState.IsValid) { blah blah }
}

The reason it’s always true is because my validation logic inside MyModel is not being called from the ViewModel on the POST.

This is probably a noob question but I have no idea. Thanks for any help.

Chris Hawkes
  • 11,923
  • 6
  • 58
  • 68
  • 1
    I haven't got time to post code, sorry, but looking into "Custom Model Binders". Create a custom model binder for `ViewModel`, that is executed when `public ActionResult Index(ViewModel model)` is called. In the custom model binder you will be able to call the validation method. – Jason Evans Oct 20 '14 at 18:08
  • 1
    Just expanding on Jason's comment, [this SO post](http://stackoverflow.com/questions/6431478/how-to-force-mvc-to-validate-ivalidatableobject) should give you an idea how to go with `Custom Model Binder`. – Michael Oct 20 '14 at 18:23
  • Uh, this isn't MVVM--it's MVC. Your "ViewModel" is a model. The controller is...the controller. And the cshtml file is the view. Model-View-Controller. MVVM frameworks for web applications typically live client side. Angular and Knockout are two examples of an MVVM client-side framework. –  Oct 20 '14 at 18:58

2 Answers2

3

Thanks for the responses. I actually talked to a co-worker who informed me that in order to get the ViewModel to post and have the validation take place for the class referenced in the viewmodel I needed to inherit from IValidatableObject

public class MyModel : IValidatableObject

than I just needed needed to pass in ValidationContext validationContext into the Validate method.

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
}

And it worked! it called the validation method for MyModel upon posting ViewModel.

Chris Hawkes
  • 11,923
  • 6
  • 58
  • 68
1

You might also look into DataAnnotations for your validation requirements; it will probably result in much cleaner code in your model:

using System.ComponentModel.DataAnnotations;

[Required(ErrorMessage="Please supply a Name")]
[RegularExpression(@"^([A-Za-z]{1,50}$")]
Public string Name { get; set; }

...for example.

Brinky
  • 418
  • 3
  • 9