Html。EnumDropdownListFor:显示默认文本

时间:2023-01-26 14:05:33

In my view I have a enumdropdownlist (a new feature in Asp.Net MVC 5.1).

在我的视图中,我有一个enumdropdownlist (Asp中的一个新特性)。净MVC 5.1)。

@Html.EnumDropDownListFor(m => m.SelectedLicense,new { @class="form-control"})

If I execute the above code I get dropdownlist for my following enum.

如果我执行上面的代码,我将得到下一个enum的下拉列表。

public enum LicenseTypes
{
    Trial = 0,
    Paid = 1
}

but by default I want my dropdownlist to have a value(custom text) and this is what I tried

但默认情况下,我希望下拉列表有一个值(自定义文本),这就是我所尝试的

@Html.EnumDropDownListFor(m => m.SelectedLicense,"Select a license" ,new { @class="form-control"})

but now the problem is when i run it, my dropdownlist looks like this Html。EnumDropdownListFor:显示默认文本 So, the default text I want to show doesn't appear by default. If a user selects "select a license" and tries to submit the form, it does show an error saying "select a license" but it doesn't show as default text. Something i need to change?

但是现在的问题是,当我运行它时,我的下拉列表看起来是这样的,我想显示的默认文本在默认情况下不会出现。如果用户选择“选择许可”并尝试提交表单,它会显示一个错误,显示“选择许可”,但不会显示默认文本。我需要改变什么?

Ps: The image is the screenshot of the page when it loads. By default it'll show Trial as selected option.

Ps:图片是页面载入时的截图。默认情况下,它将以选定的选项显示试验。

5 个解决方案

#1


72  

Try to change the Index of LicenseTypes start from 1 not 0 like below:

试着改变被许可方的指数,从1开始,而不是如下:

public enum LicenseTypes
{
    Trial = 1,
    Paid = 2
}

Then you can use Range attribute to validate the selected license type like below:

然后您可以使用Range属性来验证所选的许可类型如下:

public class YourViewModel
{
     //Other properties
     [Range(1,int.MaxValue,ErrorMessage = "Select a correct license")]
     public LicenseTypes LicenseTypes { get; set; }
}

Finally, in your view:

最后,在你的观点:

   @Html.EnumDropDownListFor(m => m.LicenseTypes,"Select a license",new { @class = "form-control"})
   @Html.ValidationMessageFor(m => m.LicenseTypes)

#2


61  

By the time your EnumDropDownListFor is rendered SelectedLicense already has the default value for the type, which is 0.

当您的EnumDropDownListFor被呈现为SelectedLicense时,类型的默认值已经为0。

Just change the type of your SelectedLicense property to a nullable enum, like so:

只需将SelectedLicense属性的类型更改为nullable enum,如下所示:

public LicenseTypes? SelectedLicense { get; set; }

This also allows you to continue using the Required attribute, which I think is significantly cleaner. The Required attribute will not allow a null response, so even though your model allows nulls, the form will not.

这也允许您继续使用所需的属性,我认为这是非常干净的。Required属性不允许空响应,因此即使您的模型允许nulls,表单也不会。

#3


14  

I have an enum:

我有一个枚举:

public enum Sex
{
    Male,
    Female
}

In my model I have:

在我的模型中:

    [DisplayName("Sex")]
    [Required]
    public Sex? Sex { get; set; }

An in the view:

一个在视图:

    @Html.EnumDropDownListFor(model => model.Sex, "Select sex", new { @class = "form-control", type = "text"})

By this I have a dropdown with default option "Select sex", but validation accepts only options provided by enum ("Male" and "Female").

这样,我就有了一个带有默认选项“Select sex”的下拉菜单,但是验证只接受enum提供的选项(“男性”和“女性”)。

In MVC3 (without EnumDropDownListFor) I used in model:

在MVC3中(没有EnumDropDownListFor)我在模型中使用:

    [DisplayName("Sex")]
    [Required(AllowEmptyStrings=false)]
    public Sex? Sex { get; set; }

    Sex = null;

    Sexes = Repository.GetAutoSelectList<Sex>("");

In view:

在视图:

    @Html.DropDownListFor(model => model.Sex, Model.Sexes, new { @class = "form-control", type = "text" })

#4


8  

The ViewModel class needs to have the default value set on the enum property for it to be the default selected public

ViewModel类需要在enum属性上设置默认值,以使其成为默认选择的公共

public class Test
    {
        public Cars MyCars { get; set; }
        public enum Cars
        {
            [Display(Name = @"Car #1")]
            Car1 = 1,
            [Display(Name = @"Car #2")]
            Car2 = 2,
            [Display(Name = @"Car #3")]
            Car3 = 3
        }

    }

Controller:

控制器:

 public class EnumController : Controller
    {
        // GET: Enum
        public ActionResult Index()
        {
            var model = new Test {MyCars = Test.Cars.Car3}; // set default value
            return View(model);
        }
        [HttpPost]
        public ActionResult Index(Test model)
        {
            .....
        }
    }

View:

观点:

@Html.BeginForm()
{
<div class="panel bg-white">
    <div class="panel-header fg-white">
        Enums
    </div>
    <div class="panel-content">
        <div class="input-control select size3">
            @Html.EnumDropDownListFor(model => model.MyCars)

        </div>
    </div>
    <input type="submit" class="button success large" />
</div>
}

#5


0  

Am I a bit late ?

我是不是有点晚了?

Changing the values of the enum type is not very satisfying.

更改enum类型的值不是很令人满意。

Neither is changing the model property to render it nullable and then add a [Required] attribute to prevent it to be nullable.

也不改变模型属性以使其为空,然后添加一个[Required]属性以防止其为空。

I propose to use the ViewBag to set the default selected value of the dropdown. The line 4 of the controller just bellow is the only important one.

我建议使用ViewBag来设置下拉菜单的默认选择值。控制器的第4行是唯一重要的。

EDIT : Ah... newbies... My first idea was to use ModelState.SetModelValue because my newbie instinct prevented me to simply try to set the desired value in the ViewBag since the dropdown was binded to the model. I was sure to have a problem: it would bind to the model's property, not to the ViewBag's property. I was all wrong: ViewBag is OK. I corrected the code.

编辑:啊……新手……我的第一个想法是使用ModelState。SetModelValue因为我的新手直觉阻止我在ViewBag中简单地设置想要的值,因为下拉菜单被绑定到模型。我肯定有一个问题:它会绑定到模型的属性,而不是ViewBag的属性。我完全错了:ViewBag是可以的。我修正了代码。

Here is an example.

这是一个例子。

Model:

模型:

namespace WebApplication1.Models {

    public enum GoodMusic {
        Metal,
        HeavyMetal,
        PowerMetal,
        BlackMetal,
        ThashMetal,
        DeathMetal // . . .
    }

    public class Fan {
        [Required(ErrorMessage = "Don't be shy!")]
        public String Name { get; set; }
        [Required(ErrorMessage = "There's enough good music here for you to chose!")]
        public GoodMusic FavouriteMusic { get; set; }
    }
}

Controller:

控制器:

namespace WebApplication1.Controllers {
    public class FanController : Controller {
        public ActionResult Index() {
            ViewBag.FavouriteMusic = string.Empty;
            //ModelState.SetModelValue( "FavouriteMusic", new ValueProviderResult( string.Empty, string.Empty, System.Globalization.CultureInfo.InvariantCulture ) );
            return View( "Index" );
        }
        [HttpPost, ActionName( "Index" )]
        public ActionResult Register( Models.Fan newFan ) {
            if( !ModelState.IsValid )
                return View( "Index" );
            ModelState.Clear();
            ViewBag.Message = "OK - You may register another fan";
            return Index();
        }
    }
}

View:

观点:

@model WebApplication1.Models.Fan
<h2>Hello, fan</h2>
@using( Html.BeginForm() ) {
    <p>@Html.LabelFor( m => m.Name )</p>
    <p>@Html.EditorFor( m => m.Name ) @Html.ValidationMessageFor( m => m.Name )</p>
    <p>@Html.LabelFor( m => m.FavouriteMusic )</p>
    <p>@Html.EnumDropDownListFor( m => m.FavouriteMusic, "Chose your favorite music from here..." ) @Html.ValidationMessageFor( m => m.FavouriteMusic )</p>
    <input type="submit" value="Register" />
    @ViewBag.Message
}

Without the "ModelState.SetModelValue or ViewBag.FavouriteMusic = string.Empty" line in the model Index action the default selected value would be "Metal" and not "Select your music..."

没有”状态。SetModelValue或ViewBag。FavouriteMusic =字符串。在模型索引操作中空行默认选择的值是“Metal”而不是“Select your music…”

#1


72  

Try to change the Index of LicenseTypes start from 1 not 0 like below:

试着改变被许可方的指数,从1开始,而不是如下:

public enum LicenseTypes
{
    Trial = 1,
    Paid = 2
}

Then you can use Range attribute to validate the selected license type like below:

然后您可以使用Range属性来验证所选的许可类型如下:

public class YourViewModel
{
     //Other properties
     [Range(1,int.MaxValue,ErrorMessage = "Select a correct license")]
     public LicenseTypes LicenseTypes { get; set; }
}

Finally, in your view:

最后,在你的观点:

   @Html.EnumDropDownListFor(m => m.LicenseTypes,"Select a license",new { @class = "form-control"})
   @Html.ValidationMessageFor(m => m.LicenseTypes)

#2


61  

By the time your EnumDropDownListFor is rendered SelectedLicense already has the default value for the type, which is 0.

当您的EnumDropDownListFor被呈现为SelectedLicense时,类型的默认值已经为0。

Just change the type of your SelectedLicense property to a nullable enum, like so:

只需将SelectedLicense属性的类型更改为nullable enum,如下所示:

public LicenseTypes? SelectedLicense { get; set; }

This also allows you to continue using the Required attribute, which I think is significantly cleaner. The Required attribute will not allow a null response, so even though your model allows nulls, the form will not.

这也允许您继续使用所需的属性,我认为这是非常干净的。Required属性不允许空响应,因此即使您的模型允许nulls,表单也不会。

#3


14  

I have an enum:

我有一个枚举:

public enum Sex
{
    Male,
    Female
}

In my model I have:

在我的模型中:

    [DisplayName("Sex")]
    [Required]
    public Sex? Sex { get; set; }

An in the view:

一个在视图:

    @Html.EnumDropDownListFor(model => model.Sex, "Select sex", new { @class = "form-control", type = "text"})

By this I have a dropdown with default option "Select sex", but validation accepts only options provided by enum ("Male" and "Female").

这样,我就有了一个带有默认选项“Select sex”的下拉菜单,但是验证只接受enum提供的选项(“男性”和“女性”)。

In MVC3 (without EnumDropDownListFor) I used in model:

在MVC3中(没有EnumDropDownListFor)我在模型中使用:

    [DisplayName("Sex")]
    [Required(AllowEmptyStrings=false)]
    public Sex? Sex { get; set; }

    Sex = null;

    Sexes = Repository.GetAutoSelectList<Sex>("");

In view:

在视图:

    @Html.DropDownListFor(model => model.Sex, Model.Sexes, new { @class = "form-control", type = "text" })

#4


8  

The ViewModel class needs to have the default value set on the enum property for it to be the default selected public

ViewModel类需要在enum属性上设置默认值,以使其成为默认选择的公共

public class Test
    {
        public Cars MyCars { get; set; }
        public enum Cars
        {
            [Display(Name = @"Car #1")]
            Car1 = 1,
            [Display(Name = @"Car #2")]
            Car2 = 2,
            [Display(Name = @"Car #3")]
            Car3 = 3
        }

    }

Controller:

控制器:

 public class EnumController : Controller
    {
        // GET: Enum
        public ActionResult Index()
        {
            var model = new Test {MyCars = Test.Cars.Car3}; // set default value
            return View(model);
        }
        [HttpPost]
        public ActionResult Index(Test model)
        {
            .....
        }
    }

View:

观点:

@Html.BeginForm()
{
<div class="panel bg-white">
    <div class="panel-header fg-white">
        Enums
    </div>
    <div class="panel-content">
        <div class="input-control select size3">
            @Html.EnumDropDownListFor(model => model.MyCars)

        </div>
    </div>
    <input type="submit" class="button success large" />
</div>
}

#5


0  

Am I a bit late ?

我是不是有点晚了?

Changing the values of the enum type is not very satisfying.

更改enum类型的值不是很令人满意。

Neither is changing the model property to render it nullable and then add a [Required] attribute to prevent it to be nullable.

也不改变模型属性以使其为空,然后添加一个[Required]属性以防止其为空。

I propose to use the ViewBag to set the default selected value of the dropdown. The line 4 of the controller just bellow is the only important one.

我建议使用ViewBag来设置下拉菜单的默认选择值。控制器的第4行是唯一重要的。

EDIT : Ah... newbies... My first idea was to use ModelState.SetModelValue because my newbie instinct prevented me to simply try to set the desired value in the ViewBag since the dropdown was binded to the model. I was sure to have a problem: it would bind to the model's property, not to the ViewBag's property. I was all wrong: ViewBag is OK. I corrected the code.

编辑:啊……新手……我的第一个想法是使用ModelState。SetModelValue因为我的新手直觉阻止我在ViewBag中简单地设置想要的值,因为下拉菜单被绑定到模型。我肯定有一个问题:它会绑定到模型的属性,而不是ViewBag的属性。我完全错了:ViewBag是可以的。我修正了代码。

Here is an example.

这是一个例子。

Model:

模型:

namespace WebApplication1.Models {

    public enum GoodMusic {
        Metal,
        HeavyMetal,
        PowerMetal,
        BlackMetal,
        ThashMetal,
        DeathMetal // . . .
    }

    public class Fan {
        [Required(ErrorMessage = "Don't be shy!")]
        public String Name { get; set; }
        [Required(ErrorMessage = "There's enough good music here for you to chose!")]
        public GoodMusic FavouriteMusic { get; set; }
    }
}

Controller:

控制器:

namespace WebApplication1.Controllers {
    public class FanController : Controller {
        public ActionResult Index() {
            ViewBag.FavouriteMusic = string.Empty;
            //ModelState.SetModelValue( "FavouriteMusic", new ValueProviderResult( string.Empty, string.Empty, System.Globalization.CultureInfo.InvariantCulture ) );
            return View( "Index" );
        }
        [HttpPost, ActionName( "Index" )]
        public ActionResult Register( Models.Fan newFan ) {
            if( !ModelState.IsValid )
                return View( "Index" );
            ModelState.Clear();
            ViewBag.Message = "OK - You may register another fan";
            return Index();
        }
    }
}

View:

观点:

@model WebApplication1.Models.Fan
<h2>Hello, fan</h2>
@using( Html.BeginForm() ) {
    <p>@Html.LabelFor( m => m.Name )</p>
    <p>@Html.EditorFor( m => m.Name ) @Html.ValidationMessageFor( m => m.Name )</p>
    <p>@Html.LabelFor( m => m.FavouriteMusic )</p>
    <p>@Html.EnumDropDownListFor( m => m.FavouriteMusic, "Chose your favorite music from here..." ) @Html.ValidationMessageFor( m => m.FavouriteMusic )</p>
    <input type="submit" value="Register" />
    @ViewBag.Message
}

Without the "ModelState.SetModelValue or ViewBag.FavouriteMusic = string.Empty" line in the model Index action the default selected value would be "Metal" and not "Select your music..."

没有”状态。SetModelValue或ViewBag。FavouriteMusic =字符串。在模型索引操作中空行默认选择的值是“Metal”而不是“Select your music…”