htmlasp.net-mvcasp.net-mvc-4razorhtml.dropdownlistfor

ASP.NET MVC @Html.DropdownListFor wrong selected value


I know there are tons of question about this (this this and this) are some of the questions I read, but I did not found anything that helped:

In my View I have

@Html.DropDownListFor(m => m.AktPriority, CustomHTMLHeper.GetPriorityDropDown(),new { @class = "form-control" })

In my helper

    public static SelectList GetPriorityDropDown()
    {

        List<SelectListItem> result = new List<SelectListItem>();
        SelectListItem low = new SelectListItem();
        low.Value = "0";
        low.Text = "Niedrig";
        SelectListItem middle = new SelectListItem();
        middle.Value = "1";
        middle.Text = "Mittel";
        SelectListItem high = new SelectListItem();
        high.Value = "2";
        high.Text = "Hoch";
        return new SelectList(new SelectListItem[] { middle, high, low }, "Value", "Text", "1");

    }

I expect the item with the value 1 to be selected but following HTML is generated:

<select name="AktPriority" id="AktPriority" class="form-control">
  <option value="1">Mittel</option>
   <option value="2">Hoch</option>
    <option value="0" selected="selected">Niedrig</option>
   </select>

I also tried setting the Selected Property to true in the helper. This did not work either.


Solution

  • You did not post your action method, but if you use DropDownListFor you need to set the "selected" value in the model:

    model.AktPriority = "1";
    
    return View(model);