views:

159

answers:

2

When I post a 'Model' object (as generated by LinqToSQL) to a controller, I can query 'ModelState.IsValid', and if there are validation attributes on any of the properties and the value doesn't validate, it will be set to 'false'.

However, ModelState.IsValid seems to always return 'true' if I'm posting a custom object of my own class, even if the properties on that class have validation attributes and are given incorrect values.

Why does this only work with DataContext model objects? What is it about these objects that makes them work with ModelState.IsValid, while normal classes don't?

How can I make it work with normal classes?


Controller code:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogIn(MyProject.Website.ViewModels.Shared.LogIn model)
{
    if (ModelState.IsValid)
        return View(model);

    // ... code to log in the user
}

ViewModel code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using MyProject.Website.Validators;
using System.ComponentModel;

public class LogIn
{

    public LogInModes LogInMode { get; set; }

    [Required] 
    [EmailAddress]
    public string EmailAddress { get; set; }

    public string Password { get; set; }

    public bool RememberMe { get; set; }

    public string ReturnUrl { get; set; }

}
A: 

Shouldn't you just try if (model.IsValid()) ??

EDIT: Sorry that would require Login class inheriting from something like Model.

David Archer
+1  A: 

Have you set DataAnnotationsModelBinder as your default model binder in Application_Start event of your Global.asax file like this?

protected void Application_Start() {
    ModelBinders.Binders.DefaultBinder = new DataAnnotationsModelBinder();
}

Becasue as far as I know, the attributes under System.ComponentModel.DataAnnotations namescape only work with that model binder.

You can also set your model binder only for that action :

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult LogIn( [ModelBinder(typeof(DataAnnotationsModelBinder))]
    Yieldbroker.Website.ViewModels.Shared.LogIn model) {
    //...
}

See this blog post and this question.

çağdaş