Reputation: 1153
Controller:
ViewBag.Category = new SelectList(this.service.GetAllCategories(), product.Category);
I'm not using Id + Name. GetAllCategories() returns only several int numbers.
When I use in a View:
@Html.DropDownList("Category", String.Empty)
everything works. Edit is ok and DropDownList shows the selected value. HTML result:
<select id="Category" name="Category">
<option value=""></option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option selected="selected">5</option>
...
</select>
But I need to use css @class so I use this code:
@Html.DropDownList("Category", (IEnumerable<SelectListItem>)ViewBag.Category, new { @class = "anything" })
HTML result:
<select class="anything" id="Category" name="Category">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
...
</select>
Unfortunately, Edit still works (I can save the value that I select) but DropDownList starts to show the default value not the value saved in the database.
Do you have any ideas what would be the problem?
Update I made an update to be more precise.
The method GetAllCategories looks like this:
public List<int> GetAllCategories()
{
List<int> categories = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
return categories;
}
Upvotes: 4
Views: 2182
Reputation: 139748
The Html.DropDownList
works quite interesting:
If you don't provide a selection list
@Html.DropDownList("Category", String.Empty)
it will look up the values for the selection from ViewData/ViewBag
based on the provided property name: Category
.
But if you provide a selection list it will look for default selected item in the ViewData/ViewBag
based on the provided property name Category
which of course will contain the list instead of the default value. To fix this you have two options:
Don't provide the selection list:
@Html.DropDownList("Category", null, new { @class = "anything" })
Or
Use a different name instead of the ViewBag
property name Category
:
@Html.DropDownList("CategoryDD", (IEnumerable<SelectListItem>)ViewBag.Category, new { @class = "anything" })
Upvotes: 6
Reputation: 8393
You can use the drop down list for html helper. Note, that the "model" you are expecting is required in the view.
@Html.DropDownListFor(model => model.savedID,
(IEnumerable<SelectListItem>)ViewBag.Category, new { @class = "anything" })
Upvotes: 0
Reputation: 13569
SelectList typelist = new SelectList(this.service.GetAllCategories(), "ProductID", "ProductName", product.Category);
ViewBag.Category=typelist;
I think from your table you have to suply the default values "ProductID" and text "ProductName" or the one you use and want to display so the list can be generated for this results.
Not sure what exactly your problem is but you may try this maybe it will solve it.
Upvotes: 0