MVC @Html.DropDownList SelectedValue does not work

coolwolf / 22/03/2018

I am new to mvc. When i create @Html.DropDownList, i see sometimes i can set SelectedValue but sometimes i can not.
I tried many solutions like creating “<select” manually, passing generic List<>, passing List<SelectListItem>, passing SelectList etc.
But no success. Razor View does no select the item which i want.
After days of searching, i found a blog entry which solve my problem.
My controller side was like that:

public ActionResult Liste(int? MyValue)
{
	if (MyValue== null || MyValue == 0) MyValue = 1;
	List<SelectListItem> _sl = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(v => new SelectListItem{Text = v.ToString(),Value = ((int)v).ToString()}).ToList();
	foreach(SelectListItem _itm in _sl)
	{
		if (_itm.Value == MyValue.Value.ToString()) _itm.Selected = true;
	}
	ViewBag.ProductType= _sl;
	ViewBag.SelValue= MyValue;
	return View();
}

and my Razor View was like that:

@Html.DropDownList("ProductType", (List<SelectListItem>)ViewBag.ProductType, new { @class = "form-control" })

normally there is no problem. Problem occurs only when i try to set selected item. This completely works.
So what is the problem then?
The problem is: The name of dropdown and viewbag constant is same. 
When i change my controller to this:

public ActionResult Liste(int? MyValue)
{
	if (MyValue== null || MyValue == 0) MyValue = 1;
	List<SelectListItem> _sl = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(v => new SelectListItem{Text = v.ToString(),Value = ((int)v).ToString()}).ToList();
	foreach(SelectListItem _itm in _sl)
	{
		if (_itm.Value == MyValue.Value.ToString()) _itm.Selected = true;
	}
	ViewBag.MyProdList= _sl;
	ViewBag.SelValue= MyValue;
	return View();
}

and View to this:

@Html.DropDownList("ProductType", (List<SelectListItem>)ViewBag.MyProdList, new { @class = "form-control" })

everything works.
I wonder, why did i not understand this before.
If anyone face same problem, i hope he/she find this blog entry and not spent lot of time as i spent.

Submit a Comment