控制器:編輯不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