在我的 MVC5 应用程序中,我有一个显示日志的页面。
我有一个下拉菜单来过滤日志记录级别,它们是:
- 全部
- 调试
- 错误
- 信息
我定义了一个名为 ErrorLevel 的枚举:
public enum ErrorLevel
{
[Description("All")]
All = 0,
[Description("Debug")]
Debug = 1,
[Description("Error")]
Error = 2,
[Description("Info")]
Info = 3
}
我在我的 View 中渲染这些,如下所示:
@Html.EnumDropDownListFor(model => model.Level)
The drop down value is blank when the page first renders - how do I have
All
as the default selected enum value when the page first renders?
我花了 20 分钟寻找如何做到这一点,但找不到如何做到这一点,有人可以帮忙吗?
最佳答案
您好,您可以在 Controller 内模型类的构造函数中轻松做到这一点。
这是完整的示例:
模态类示例:
public class SampleModel
{
public ErrorLevel level{ get; set; }
}
枚举:
public enum ErrorLevel
{
[Description("All")]
All = 0,
[Description("Debug")]
Debug = 1,
[Description("Error")]
Error = 2,
[Description("Info")]
Info = 3
}
一些 Controller :
public class HomeController : Controller
{
public ActionResult Index()
{
SampleModel samplemodel= new SampleModel {level= level.All}; //you can set any value which you want as default
return View("View",samplemodel);
}
}
希望以上代码对您有所帮助
谢谢
卡提克
关于c# - 如何使用 EnumDropDownListFor 获得默认选定的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44707288/