asp.net-mvcselectviewhtml.dropdownlistforselectlistitem

MVC C# DropDownListFor has value of previous select


C# fiddle screenshot

https://dotnetfiddle.net/MadhI5

Model:

public class IndexViewModel
{
    public List<SelectListItem> Sel { get; set; }
    public string Val1 { get; set; }
    public string Val2 { get; set; }
    public string Val3 { get; set; }
    public string Val4 { get; set; }
    public string Val5 { get; set; }
}

Controller:

public ActionResult Index()
{
    var vm = new IndexViewModel();

    vm.Sel = new List<SelectListItem>();
    vm.Sel.Add(new SelectListItem() { Text = "Opt1", Value = "1" });
    vm.Sel.Add(new SelectListItem() { Text = "Opt2", Value = "2" });
    vm.Sel.Add(new SelectListItem() { Text = "Opt3", Value = "3" });

    vm.Val1 = "3";
    vm.Val2 = null;
    vm.Val3 = "1";
    vm.Val4 = null;
    vm.Val5 = "3";

    return View(vm);
}

View:

@model HelloWorldMvcApp.IndexViewModel
@{
    Layout = null;
}

@Html.DropDownListFor(m => m.Val1, Model.Sel, "-")
@Html.DropDownListFor(m => m.Val2, Model.Sel, "-")
@Html.DropDownListFor(m => m.Val3, Model.Sel, "-")
@Html.DropDownListFor(m => m.Val4, Model.Sel, "-")
@Html.DropDownListFor(m => m.Val5, Model.Sel, "-")

The selected values are

Look at the fiddle demo. Why Val2 and Val4 is not null in View? It`s a framework bug?


Solution

  • ...
    vm.Val1 = "3";
    vm.Val2 = "";
    vm.Val3 = "1";
    vm.Val4 = "";
    vm.Val5 = "3";
    ...
    

    Using "" instead of null works