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

标签 asp.net asp.net-mvc asp.net-mvc-3 razor

Controller :

ViewBag.Category = new SelectList(this.service.GetAllCategories(), product.Category);

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

当我在 View 中使用时:
@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;
        }

最佳答案

Html.DropDownList作品很有趣:
如果您不提供选择列表

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

它将从 ViewData/ViewBag 中查找选择的值基于提供的属性名称:Category .
但是如果你提供一个选择列表,它会在 ViewData/ViewBag 中寻找默认选择的项目。基于提供的属性名称 Category这当然将包含列表而不是默认值。要解决此问题,您有两个选择:

不提供选择列表:
@Html.DropDownList("Category", null, new { @class = "anything" })
或者
使用不同的名称而不是 ViewBag属性(property)名称Category :
@Html.DropDownList("CategoryDD", (IEnumerable<SelectListItem>)ViewBag.Category, new { @class = "anything" })

关于asp.net - 编辑不适用于 Html.DropDownList 和 @class 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8098361/

相关文章:

c# - 使用 SignalR 推送事件 "DB Data Changes"

c# - Jquery Ajax 和 asp.net WebMethod

c# - Visual Studio 2017在调试时尝试使用IP连接到本地Mysql

c# - 在 MVC HTML Helper 中将 Javascript 代码与 HTML 一起注入(inject)

asp.net-mvc - 带有输出参数的 ExecuteSqlCommand

asp.net - 将 Web.Config 移植到 ASPNET5

c# - "System.Web.UI.MasterPage does not contain a definition..."ASP.NET 错误

entity-framework - 验证复选框 - 前端 MVC3

c# - EntityFramework 存储库从接口(interface)和抽象类 : how to use dependency inject on ASP. NET MVC 驱动

asp.net-mvc-3 - asp.net 数据注释字段长度