gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:36:26 24 4
gpt4 key购买 nike

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/

24 4 0