编辑不适用于Html.DropDownList和@class属性

nub*_*ubm 4 asp.net asp.net-mvc razor asp.net-mvc-3

控制器:

ViewBag.Category = new SelectList(this.service.GetAllCategories(), product.Category);
Run Code Online (Sandbox Code Playgroud)

我没有使用Id + Name.GetAllCategories()只返回几个int数.

当我在视图中使用时:

@Html.DropDownList("Category", String.Empty)
Run Code Online (Sandbox Code Playgroud)

一切正常.编辑正常,DropDownList显示所选值.HTML结果:

<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>
Run Code Online (Sandbox Code Playgroud)

但我需要使用css @class,所以我使用这段代码:

@Html.DropDownList("Category", (IEnumerable<SelectListItem>)ViewBag.Category, new { @class = "anything" })
Run Code Online (Sandbox Code Playgroud)

HTML结果:

<select class="anything" id="Category" name="Category">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
...
</select>
Run Code Online (Sandbox Code Playgroud)

不幸的是,编辑仍然有效(我可以保存我选择的值),但DropDownList开始显示默认值而不是数据库中保存的值.

你有什么想法会有什么问题吗?

更新 我做了更新更准确.

GetAllCategories方法如下所示:

public List<int> GetAllCategories()
        {
            List<int> categories = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

            return categories;
        }
Run Code Online (Sandbox Code Playgroud)

nem*_*esv 6

这项Html.DropDownList工作很有意思:
如果你没有提供选择清单

@Html.DropDownList("Category", String.Empty)
Run Code Online (Sandbox Code Playgroud)

它将ViewData/ViewBag根据提供的属性名称查找选择的值:Category.
但是,如果您提供选择列表,它将ViewData/ViewBag根据提供的属性名称查找默认选定项目Category,当然将包含列表而不是默认值.要解决此问题,您有两种选择:

不提供选择列表:

@Html.DropDownList("Category", null, new { @class = "anything" })


使用其他名称而不是ViewBag属性名称Category:

@Html.DropDownList("CategoryDD", (IEnumerable<SelectListItem>)ViewBag.Category, new { @class = "anything" })