控制器:编辑不Html.DropDownList工作,@class属性
ViewBag.Category = new SelectList(this.service.GetAllCategories(), product.Category);
我不使用编号+姓名。 GetAllCategories()只返回几个int数字。
当我在一个视图中使用:
@Html.DropDownList("Category", String.Empty)
一切正常。编辑正常,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>
但我需要用css @class所以我用这个代码:
@Html.DropDownList("Category", (IEnumerable<SelectListItem>)ViewBag.Category, new { @class = "anything" })
HTML结果:
<select class="anything" id="Category" name="Category">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
...
</select>
不幸的是,编辑仍然有效(我可以保存我选择),但的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;
}
你是男人。我完全忽略了null的可能性(它肯定是类似于“codeblindness”;-)。 @ Html.DropDownList(“Category”,null,new {@class =“anything”})解决了这个问题。 – nubm