c# - 如何使用 EnumDropDownListFor 获得默认选定的枚举?

标签 c# asp.net-mvc enums

在我的 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/

相关文章:

c# - Mysql 备份超时过期 - C#

c# - 如何使用 C# 远程对 Stack Overflow 帖子投反对票?

c# - 二维数组未获得预期输出

c# - 内存映射文件 .NET

javascript - 无法在 PDFjs 中指定 pdf.worker.js 的自定义路径

swift - 对 Swift 中枚举的误解

javascript - 接收 json 异步响应的最有效方法?

javascript - 使用 JavaScript 提交 Ajax.BeginForm()

java - 在 switch-case 中使用枚举值的字符串表示

enums - 解构枚举时是否可以向上转换为特征?