DarthVader
DarthVader

Reputation: 55022

MVC drop down from select

<select name="BasicInfo.Month">
    <option value="na">Month</option>
    <option value="1">January</option>
    <option value="2">February</option>
    <option value="3">March</option>
    <option value="4">April</option>
    <option value="5">May</option>
    <option value="6">June</option>
    <option value="7">July</option>
    <option value="8">August</option>
    <option value="9">September</option>
    <option value="10">October</option>
    <option value="11">November</option>
    <option value="12">December</option>
</select>

I have this code which I copied from somewhere, I need to create a dropdown list MVC style, so I can mark the selected one etc. how can I convert this to something that MVC uses?

Upvotes: 0

Views: 1247

Answers (2)

Erwin
Erwin

Reputation: 4817

In your view model you can add the following property:

public IEnumerable<SelectListItem> Months
{
    get 
    {
        return DateTimeFormatInfo
               .InvariantInfo
               .MonthNames
               .Select((month, index) => new SelectListItem
               {
                   Value = (index + 1).ToString(),
                   Text = month
               });
    }
}

And in your view point to that Months propery.

<%= Html.DropDownListFor(Model.Months) %>

The advantage of this approach is that the month names will be translated if you change the language settings of your application.

Upvotes: 3

Paul Fleming
Paul Fleming

Reputation: 24526

In it's simplest form:

@Html.DropDownListFor(m => m.BasicInfo.Month, new List<SelectListItem>
{
    new SelectListItem { Text = "Month", Value = "na" },
    new SelectListItem { Text = "January", Value = "1" },
    new SelectListItem { Text = "February", Value = "2" },
    new SelectListItem { Text = "March", Value = "3" },
    new SelectListItem { Text = "April", Value = "4" },
    new SelectListItem { Text = "May", Value = "5" },
    new SelectListItem { Text = "June", Value = "6" },
    new SelectListItem { Text = "July", Value = "7" },
    new SelectListItem { Text = "August", Value = "8" },
    new SelectListItem { Text = "September", Value = "9" },
    new SelectListItem { Text = "October", Value = "10" },
    new SelectListItem { Text = "November", Value = "11" },
    new SelectListItem { Text = "December", Value = "12" }
})

If you really want to, you can automate the list creation using the DateTime object. That way you also get culture specific month names.

Your model would be:

public class MyModel
{
    public BasicInfoModel BasicInfo { get; set; }
}
public class BasicInfoModel
{
    public string Month { get; set; }
}

Upvotes: 1

Related Questions