Monday, October 3, 2011

Selected Items with HtmlHelpers

I came across an odd 'feature' of MVC Html Helpers today: Even if you explicitly provide a selected value when you call an option-based Helper, there's no guarantee that selected value will be used.

Suppose you are creating a view - an edit page for a Book. You declare something like this in your view. Note that we are passing in a new Author object as our currently selected item - so it shouldn't match anything and no items should be selected:

<% var selectList = 
    new SelectList(Model.Authors, "Id", "Name", new Author()); %>

<%=Html.DropDownList("book.Author.Id", selectList, 
    "Please select")%>

The fourth argument to your SelectList constructor is a new Author object. As such when you view your edit page you would expect the drop-down to default to "Please select".

In reality though, the drop-down defaults to the author associated in your model..? This may be the behaviour you normally want from an edit page, but when your business rules suggest that the field not be pre-populated, you can't live up to it without a mild hack.

What's happening is the Html Helper is looking at your View Model object, for an item that looks like the first argument: "book.Author.Id"

When it finds it, the Helper is favouring that Id value over your suggestion. Not exactly putting you in the driving seat is it?

One workaround? It's not the nicest-looking, but set the View Model value to what you want just before calling the Helper:

Model.Book.Author = new Author();
<% var selectList = 
    new SelectList(Model.Authors, "Id", "Name", new Author()); %>

<%=Html.DropDownList("book.Author.Id", selectList, 
    "Please select")%>

It may not be pretty, but it works.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.