如何在EnumDropDownListFor中设置选定的值? [英] How to set the selected value in EnumDropDownListFor?

查看:117
本文介绍了如何在EnumDropDownListFor中设置选定的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVC 5.2.0,并且尝试使用新的 Html.EnumDropDownListFor 。这就是我设置值的方式:

I'm using MVC 5.2.0 and I'm trying to use the new Html.EnumDropDownListFor. This is how I'm setting the values:

//Model
public class MyModel {
    public int SelectedEnumId { get; set; }
    public TestEnum MyEnum { get; set; }
}

//Enum
public enum TestEnum : int
{
    name1 = 1,
    name2 = 2
}

//View
@Html.EnumDropDownListFor(model => model.MyEnum,new { @class = "form-control" })

这正在起作用,并且正在显示值。但是如何设置所选值(SelectedEnumId)?

This is working and the values are being displayed. But how do I set the selected value (SelectedEnumId)?

通常我会使用

//Not enum
@Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.myvalues, "Value", "Text"))

是否可以使用MVC 5.1-5.2中的新Helper来做到这一点?还是我必须为此创建一个扩展方法?

Is there a way to do this with the new Helper in MVC 5.1-5.2? Or I have to create a Extension method for this?

推荐答案

据我所知,只需确保您想要的值是在调用之前,已在模型中设置了选定的

As far as I know just make sure the value you want to be selected is set in your Model before you call

//Controller:
...
myModel.TestEnum = TestEnum.name2;
...

//On your view
...
@Html.EnumDropDownListFor(model => model.TestEnum);
...

这篇关于如何在EnumDropDownListFor中设置选定的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆