【问题标题】:How do I have a default selected enum using EnumDropDownListFor?如何使用 EnumDropDownListFor 选择默认枚举?
【发布时间】:2017-06-22 18:52:44
【问题描述】:

在我的 MVC5 应用程序中,我有一个显示日志的页面。

我有一个过滤日志级别的下拉菜单,它们是:

  • 全部
  • 调试
  • 错误
  • 信息

我已经定义了一个名为 ErrorLevel 的枚举:

public enum ErrorLevel
{
    [Description("All")]
    All = 0,

    [Description("Debug")]
    Debug = 1,

    [Description("Error")]
    Error = 2,

    [Description("Info")]
    Info = 3
}

我正在像这样在我的视图中呈现这些:

@Html.EnumDropDownListFor(model => model.Level)

页面首次呈现时下拉值是空白 - 我如何在页面首次呈现时将All 作为默认选择的枚举值

我花了 20 分钟寻找如何做到这一点,但找不到如何做到这一点,有人可以帮忙吗?

【问题讨论】:

    标签: c# asp.net-mvc enums


    【解决方案1】:

    您好,您可以在控制器中模型类的构造函数中轻松做到这一点。

    这是完整的示例:

    模态类示例:

     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
    }
    

    一些控制器:

    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);
        }
    }
    

    希望上面的代码对你有帮助

    谢谢

    卡提克

    【讨论】:

      【解决方案2】:

      您可以通过在视图中调用它之前在模型中设置枚举来做到这一点。

      控制器

       model.Level = ErrorLevel.All;
      

      【讨论】:

        猜你喜欢
        • 2018-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-24
        • 2023-03-18
        相关资源
        最近更新 更多