How to set the selected value in EnumDropDownListFor?

后端 未结 3 1115
春和景丽
春和景丽 2020-12-19 02:31

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          


        
相关标签:
3条回答
  • 2020-12-19 02:49

    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);
    ...
    
    0 讨论(0)
  • 2020-12-19 03:05

    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;
    }
    
    0 讨论(0)
  • 2020-12-19 03:06

    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>
    
    0 讨论(0)
提交回复
热议问题