2011-11-11 35 views
4

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

回答

6

Html.DropDownList作品很有趣:
如果你不提供一個選擇清單

@Html.DropDownList("Category", String.Empty) 

它會查找值從ViewData/ViewBag基於所提供的屬性名稱的選擇:Category
但是,如果你提供一個選擇列表它會尋找默認選擇的項目的基礎上所提供的屬性名CategoryViewData/ViewBag這當然會包含列表,而不是默認值。爲了解決這個問題,你有兩個選擇:

不提供選擇列表:

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

或者
使用,而不是ViewBag屬性名Category不同的名稱:

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

+0

你是男人。我完全忽略了null的可能性(它肯定是類似於「codeblindness」;-)。 @ Html.DropDownList(「Category」,null,new {@class =「anything」})解決了這個問題。 – nubm

0
SelectList typelist = new SelectList(this.service.GetAllCategories(), "ProductID", "ProductName", product.Category); 
ViewBag.Category=typelist; 

我想從你的表,你必須suply默認值「產品ID」和文本「產品名稱」,或者你使用一個並希望顯示因此可以爲此結果生成列表。

不知道究竟你的問題,但您可以嘗試這個也許會解決這個問題。

+0

類別只是保存在數據庫中的int值。這不是FK。 – nubm

+0

我認爲你需要提供價值和文本的價值列表,否則你可能不會得到列表中的項目。 –

0

您可以使用下拉列表中的HTML幫助。請注意,您期望的「模型」在視圖中是必需的。

@Html.DropDownListFor(model => model.savedID, 
    (IEnumerable<SelectListItem>)ViewBag.Category, new { @class = "anything" }) 
+0

我試過這個,但行爲沒有改變。 – nubm