I'm stuck on what I thought was going to be a very simple task in ASP.Net MVC2.
I need to apply a background color to certain SELECT OPTION elements. To generate the dropdowns we're using the Html.DropDownList and Html.ListBox html helpers, and ideally I'd like to continue using these so I don't have to deal with re-binding the selected items from the form collection when the form is submitted and redisplayed.
For reasons I won't go into the Html helpers are called from within another html helper that we've written, so they're not in the view. The code looks like this...
var setOfOptions = question.AnswerList.Values.Select(x => new SelectListItem(){
Value = x.ID.ToString(),
Text = x.Caption + " - " + x.Style,
Selected = question.Answers.Contains((object)x.ID)
});
answerlistHtml = html.DropDownList(question.GetQualifiedId(), setOfOptions, "Please select...", new { @class = "superselect disabled" }).ToHtmlString();
So here we're turning a collection of our "AnswerListValue" objects into an IEnumerable, and generating SELECT html from that. However this gives me no way to get x.Style into the SELECT OPTION element - because there's no HtmlAttributes property on SelectListItem. Here's what I want the SELECT to look like...
<select id="whatever" name="whatever">
开发者_如何学Python <option value="1" class="mystyle1">val1</option>
<option value="2" class="mystyle2">val2</option>
<option value="3" class="mystyle3">val3</option>
</select>
The obvious answer here is to make my own SelectListItemWithAttributes object - but I can't figure out how to create a DropDownListWithAttributes object, even after examining the MVC2 source code.
What would you do in this situation?
You would not need to 'create' your own DropDown helper. You would need to extend the default DropDown Helper. It`s pretty simple and thats the best thing about MVC.
I would suggest you check the answer of Creating a SelectListItem with the disabled="disabled" attribute to get an idea.
精彩评论