How to set the selected value in EnumDropDownListFor?

故事扮演 提交于 2019-11-30 08:59:38

问题


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

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

Normally I would use

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

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?


回答1:


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



回答2:


Could NOT get the option selected in the controller to display on the front end either, so had to resort to setting a temporary hidden input and used jQuery to update on the client side:

<div class="form-group">
@Html.LabelFor(model => model.MyEnum, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
    @Html.EnumDropDownListFor(model => model.MyEnum, "Select name", new { @class = "form-control" })
    @Html.ValidationMessageFor(model => model.MyEnum, "", new { @class = "text-danger" })
</div>
@Html.Hidden("MyEnumTemp", (int)Model.MyEnum)

<script>
    $(function () {
        $("#MyEnum").val($("#MyEnumTemp").val());
    });
</script>



回答3:


Just Use This in Your Controller, It works like a charm

MyModel.TestEnum = (TestEnum)SelectedEnumId;

Not This will work fine assuming the case, that SelectedEnumId > 0.

if(SelectedEnumId > 0) {
   MyModel.TestEnum = (TestEnum)SelectedEnumId;
}


来源:https://stackoverflow.com/questions/24770756/how-to-set-the-selected-value-in-enumdropdownlistfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!