In an ASP.NET MVC 3 Web site I have a view with the following code (Razor):
@Html.DropDownList("SessionYear", new SelectList(ViewBag.SessionYears as System.Collections.IEnumerable, "", "", Model.SessionYear), String.Empty)
ViewBag.SessionYears
is an IEnumerable<int>
.
The output is something like this:
<select id="SessionYear" name="SessionYear"><option value=""></option>
<option>2013</option>
<option selected="selected">2012</option>
<option>2011</option>
<option>2010</option>
</select>
That's great, however, what I'd like to do now is add a bit of text to the text displayed in the drop down list, so each option looks a little like this:
<option>2013-2014</option>
<option selected="selected">2012-201开发者_开发问答3</option>
I've tried playing around with the different options, but none are working, and I've exhausted the overloads.
Can I do this with the DropDownList helper, or do I need to implement this in a different way?
EDIT: And while I could probably convert SessionYears to an object that has an int and string to resolve this, I'd prefer not to. But if that's what I've got to do, that's what I'll do.
EDIT 2:
The code I'd expect to work is:
@Html.DropDownList("SessionYear", new SelectList(ViewBag.SessionYears as System.Collections.IEnumerable, "", (Model.SessionYear + "-" + (Model.SessionYear + 1)), Model.SessionYear), String.Empty)
However, I get the following error:
DataBinding: 'System.Int32' does not contain a property with the name '2012-2013'.
Which I suppose makes sense, since Model.SessionYear is an int. This is also why I'm thinking I have to create a new object that contains SessionYear as an int and then some other property that contains (SessionYear + "-" + (SessionYear + 1))
(as I've done in the past with other models).
But I would expect for there to be an easier way.
I am not sure if I'm understanding the question right but why aren't you setting the dataValueField and dataTextField?
Maybe build your SelectList something like this:
@Html.DropDownList("SessionYear", new SelectList(ViewBag.SessionYears as System.Collections.IEnumerable, Model.SessionYear, Convert.ToChar(Model.SessionYear) + Convert.ToChar(Model.SessionYear + 1), Model.SessionYear), String.Empty)
精彩评论