0

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; }

}
1
  • 1
    I suspect it's not the framework, but without a little code it's hard to tell what the problem is. Commented Jul 25, 2009 at 13:06

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.