views:

416

answers:

1

This seems like a really basic scenario, but I think it doesn't have a happy ending.

I have a simple project class:

public class Project 
{

    [Required(ErrorMessage = "Project title is required")]
    [DisplayName("Project Title")]
    public string Title { get; set; }

    [DisplayName("Related Categories")]
    public Category Categories { get; set; }

}

I want to ensure at least one related Category is selected. How can I validate this in the view, using Html.EnableClientValidation(), and decorators in the model? If this isn't possible, what is the fallback?

Equally frustrating, and probably an hindrance to validation is that I can't do...

<%= Html.ListBoxFor(m => m.Project.Categories,
                new SelectList(Model.Categories, "Id", "Name"))%>

...because this will attempt to associate the Project.Categories form value (a string array) to what should be a Category type, but won't be able to (I get an error "The parameter conversion from type 'System.String' to type failed because no type converter can convert between these types"). Therefore, I have to change the form name to something like m.Categories, thus disassociating from the Product class, and therefore any validation logic I would like to decorate it with.

Wow, to me this is crazy. We can't validate a simple multiselect list, using MVC2 decorators?

A: 

I'm going to put in my attempt at an answer, since this is what I'm now doing:

In my view model, I put:

    [Required(ErrorMessage = "A category is required")]
    public IEnumerable<Category> Categories { get; set; }

And the validation will occur in the UI. However, the modelstate still doesn't show up as invalid on the action... because the binding naming isn't matching up exactly, so this approach certainly isn't very solid as-is, but I think that can be worked out.

Also, this leads to an interesting point about possibly using 1:1 Action:ViewModel relationship. By doing so, you can set view specific validation in your View Model. This is different than relying on validating entities, which would be part of broader model validation, which is the direction MVC 2 is going for final release.

Of relevance:

Model validation in MVC 2 RC 2: http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html

1:1 View Model:Action approach: http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/06/29/how-we-do-mvc-view-models.aspx

Roger Rogers

related questions