Saturday, September 24, 2011

data-placeholder in MVC3

September 24, 2011 Posted by Jason Irwin , 1 comment
I ran into an interesting problem this evening with a very quick fix. I’m using the very neat chosen Javascript plugin (link) to add some aesthetic and functional sugar to a website’s existing dropdowns.

Anyhow, adding default text support (e.g. “Please choose an option”) to a multiple select dropdown is achievable using data-placeholder like this:
<select data-placeholder="Choose a country..." style="width:350px;" multiple class="chzn-select"">
Problem is, I am using ASP.NET MVC’s helper syntax to create my dropdownlists and “data-placeholder” is invalid syntax due to the dash character. The following does not work:
@Html.DropDownListFor(m => m.SelectedProductIDs, Model.AvaliableProducts.ToSelectList("ID","Name"), new { @class = "chzn-select", data-placeholder="Please select a product" })
Happily, Microsoft pulled a rabbit out of the hat and as of MVC3 underscores in html attribute properties are automatically converted to dashes, meaning that this:
@Html.DropDownListFor(m => m.SelectedProductIDs, Model.AvaliableProducts.ToSelectList("ID","Name"), new { @class = "chzn-select", data_placeholder="Please select a product" })
will generate something like this, with the place_holder converted to place-holder
<select class="chzn-select chzn-done" data-placeholder="Please select a product" id="SelectedProductIDs" name="SelectedProductIDs" style="display: none; ">

1 comments: