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
Val1
: 3 (correct)Val2
: 3 (should be "-")Val3
: 1 (correct)Val4
: 1 (should be "-")Val5
: 3 (correct)Look at the fiddle demo. Why Val2 and Val4 is not null in View? It`s a framework bug?
...
vm.Val1 = "3";
vm.Val2 = "";
vm.Val3 = "1";
vm.Val4 = "";
vm.Val5 = "3";
...
Using "" instead of null works