gpt4 book ai didi

c# - Html.EnumDropDownListFor 根据枚举变量的值设置选定的列表项

转载 作者:太空宇宙 更新时间:2023-11-03 12:50:20 25 4
gpt4 key购买 nike

这可能是重复的,所以我已经指出了我从这个网站上阅读的哪些地方让我取得了一些进步...

我有一个定义如下的模型:

public enum RequestType
{
[Display(Name = "Lovely Cold Beer")]
Beer = 0,
[Display(Name = "Warm Tea")]
Tea = 1,
[Display(Name = "Milky Coffee")]
Coffee= 2
}

基于 URL,我有一个变量将用于自动选择适当的列表项,例如

http://example.com/Request/Tea

将在 Controller 中执行此操作...

ViewBag.RequestType = RequestType.Tea.ToString();
return View("Index");

在我看来,我有一个变量来读回这个值,然后显示适当的内容:

if (ViewBag.RequestType != null)
{
reqType = Enum.Parse(typeof(RequestType), ViewBag.RequestType);
}

在此 View 中,我使用以下方法创建了一个下拉列表:

@Html.EnumDropDownListFor(model => model.RequestType, htmlAttributes: new { @onchange = "YadaYada();" })

这使用为每个 Enum 定义的 Display Name 值呈现列表。我需要的是在呈现页面时自动选择与 reqType 的值匹配的适当列表项。

根据我的研究,我发现我可以像这样传递变量:

@Html.EnumDropDownListFor(model => model.RequestType, reqType.ToString(), htmlAttributes: new { @onchange = "YadaYada();" })

但这会创建一个包含枚举值而不是显示名称的新列表项,例如

Tea <-- This should not be created, instead 'Warm Tea' should be selected
Lovely Cold Beer
Warm Tea
Milky Coffee

我的整个方法可能是错误的,因为我是 MVC 的新手,但我欢迎提出建议来修复它!我不明白为什么在 Controller 中,在枚举值上使用 ToString 会产生与在 EnumDropDownListFor 方法中执行相同操作的不同结果。

最佳答案

EnumDropDownListFor() 方法的第二个参数 (reqType.ToString()) 使用 overload它添加了一个 optionLabel(一个带有用于验证的 null 值的选项)。它不设置所选选项的值。

MVC 的模型绑定(bind)功能通过绑定(bind)到您的属性来工作,并且由于您的 RequestType 的默认值为 "Beer" ,因此将选择该选项。

例如,在将模型传递给 View 之前,您需要在模型中设置属性的值(假设您有一个用于 /Request/{request} 的特定路由)

public ActionResult Request(RequestType request)
{
var model = new MyModel
{
RequestType = request
};
return View(model);
}

关于c# - Html.EnumDropDownListFor 根据枚举变量的值设置选定的列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35800531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com