2011-11-11 37 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