Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Razor - use @Html.DropDownListFor() for the 12 months of the year

I am quite new to the HTML helper extensions in MVC, let alone in Razor, and I'm looking for a simple, neat way to display a dropdown list for the 12 months of the year, with the value as the number and the text the "MMM" representation of the date.

So the HTML at the end should be like:

<select>
  <option value="1">Jan</option>
  <option value="2">Feb</option>
  <option value="3">Mar</option>
  <!-- etc -->
</select>

Is it possible to do this entirely in the view? I need an answer that users the @Html.DropDownListFor() so I can take advantage of automatic model binding. I get close with the line of code below, but it doesn't have the distinct values.

@Html.DropDownListFor(model => Model.DobMonth, new SelectList(Enumerable.Range(1,12).Select(r => new DateTime(2000, r, 1).ToString("MMM"))), "- -")

For non-technical reasons, I can't use a jQuery datepicker.

like image 632
Mick Byrne Avatar asked Nov 30 '22 23:11

Mick Byrne


1 Answers

You are almost there, the problem is that if you don't provide the dataValue and dataText parameters when creating the SelectList it will just call ToString on the items and use them as the option's text.

What you need is to return Text, Value pairs from your select:

@Html.DropDownListFor(model => Model.DobMonth, new SelectList(
        Enumerable.Range(1, 12)
            .Select(r => new
                             {
                                Text = new DateTime(2000, r, 1).ToString("MMM"), 
                                Value = r.ToString()
                             }),
        "Value", "Text", Model.DobMonth))

If you want to have an "empty" item you need to add it manually:

@Html.DropDownListFor(model => Model.DobMonth, new SelectList(
        new [] { new { Text = "- -", Value = (string)null } }.Concat(
        Enumerable.Range(1, 12)
            .Select(r => new
                             {
                                Text = new DateTime(2000, r, 1).ToString("MMM"), 
                                Value = r.ToString()
                             })),
        "Value", "Text", Model.DobMonth))
like image 179
nemesv Avatar answered Dec 10 '22 22:12

nemesv