Robert Koritnik
Robert Koritnik

Reputation: 105059

Model validation with enumerable properties in Asp.net MVC2 RTM

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(ErrorMessage = "At least one editor is 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)
{
    if (!this.Model.IsValid)
    {
        // invalid processing
    }
    // valid processing
}

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

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. And since users provide User.Id, the whole User object instance is being validated. Which doesn't bother me, as long I would know how to exclude other properties' validation.

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?

One possible solution

I could create a separate view model for User just for the sake of entering MyModel objects. I would put actual validation attributes and omit properties I don't need.

public class MyModelUser
{
    [Required]
    public int Id { get; set; }
}

Upvotes: 1

Views: 938

Answers (1)

Robert Koritnik
Robert Koritnik

Reputation: 105059

I ended up using a separate view model (as described in One possible solution in my question), that can be fully validated. It's a workaround and I would still like to know how to do it properly.

Upvotes: 1

Related Questions