Model validation with enumerable properties in Asp.net MVC2 RTM

Posted by Robert Koritnik on Stack Overflow See other posts from Stack Overflow or by Robert Koritnik
Published on 2010-03-18T23:09:13Z Indexed on 2010/03/18 23:21 UTC
Read the original article Hit count: 887

I'm using DataAnnotations attributes to validate my model objects. My model class looks similar to this:

public class MyModel
{
    [Required]
    public string Title { get; set; }

    [Required]
    public List<User> Editors { get; set; }
}

public class User
{
    public int Id { get; set; }

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

    [Required]
    [DataType(DataType.Email)]
    public string Email { get; set; }
}

My controller action looks like:

public ActionResult NewItem(MyModel data)
{
    //...
}

User is presented with a view that has a form with:

  • a text box with dummy name where users enter user's names. For each user they enter, there's a client script coupled with ajax that creates an <input type="hidden" name="data.Editors[0].Id" value="userId" /> for each user entered (enumeration index is therefore not always 0 as written here), so default model binder is able to consume and bind the form without any problems.
  • a text box where users enter the title

Since I'm using Asp.net MVC 2 RTM which does model validation instead of input validation I don't know how to avoid validation errors.

The thing is I have to use BindAttribute on my controller action. I would have to either provide a white or a black list of properties. It's always a better practice to provide a white list. It's also more future proof.

The problem

My form works fine, but I get validation errors about user's FullName and Email properties since they are not provided. I also shouldn't feed them to the client (via ajax when user enters user data), because email is personal contact data and is not shared between users.

If there was just a single user reference on MyModel I would write

[Bind(Include = "Title, Editor.Id")]

But I have an enumeration of them. How do I provide Bind white list to work with my model?

© Stack Overflow or respective owner

Related posts about asp.net-mvc-2

Related posts about asp.net-mvc-2-rtm