0

I have the following code in the controller:

 ViewBag.CategoryName = new SelectList(catList, "key", "value");

where catList is a Dictionary where key is of type string and value is of type string. This dictionary is populated properly and contains actual values (confirmed and tested).

In my view I have the following line of code:

 @Html.DropDownListFor(model => model.CategoryName, (SelectList)ViewBag.CategoryName)

But when I run the page for some reason the actual value for the model's category name is not selected in the drop down list. Can anyone tell me what is the issue here? My model definitely has a category name and that name is in the list of values for the drop down list. The character's case is the same...

4

1 回答 1

0

Apparently the issue here is that the name of the ViewBag object CANNOT be the same as the name of the model property. In my case I named both the property and the Viewbag instance as CategoryName. When I change the code to:

 ViewBag.Categories = new SelectList(catList, "key", "value");

and

 @Html.DropDownListFor(model => model.CategoryName, (SelectList)ViewBag.Categories)

it works just fine. I'm not sure exactly why is this, probably has something to do with the model binding dictionary but this is the reason for sure. Can anyone explain what is actually happening behind the curtain here and why is this naming a problem?

于 2013-01-09T15:46:55.090 回答