Search code examples
razorhtml.dropdownlistforselectedvalue

set dropdown selected value in razor


I have dropdown of month as follows

var month=new SelectList(
        new List<SelectListItem>
        {
            new SelectListItem { Selected = true, Text = "All Months", Value = ""},
            new SelectListItem { Selected = false, Text = "January", Value = "01"},
            new SelectListItem { Selected = false, Text = "February", Value = "02"},
            new SelectListItem { Selected = false, Text = "March", Value = "03"},
            new SelectListItem { Selected = false, Text = "April", Value = "04"},
            new SelectListItem { Selected = false, Text = "May", Value = "05"},
            new SelectListItem { Selected = false, Text = "June", Value = "06"},
            new SelectListItem { Selected = false, Text = "July", Value = "07"},
            new SelectListItem { Selected = false, Text = "August", Value = "08"},
            new SelectListItem { Selected = false, Text = "September", Value = "09"},
            new SelectListItem { Selected = false, Text = "October", Value = "10"},
            new SelectListItem { Selected = false, Text = "November", Value = "11"},
            new SelectListItem { Selected = false, Text = "December", Value = "12"}

        }, "Value" , "Text", 1);
        @Html.DropDownList("drpMonth", @month, new { @class = "dropdown", @onchange = "OnDropdownChange(this.value,'month')", @selected = @ViewData["month"]})

How do I set the selected value which is equal to ViewData["month"]?


Solution

  • Try this:

     @Html.DropDownList("drpMonth", new SelectList(month,"Value","Text",ViewData["month"]), new { @class = "dropdown", @onchange = "OnDropdownChange(this.value,'month')"})