ASP.MVC Enum DropDownListFor

207 views Asked by At

I have a very special failure on my EnumHelper for DropDownListFor. I write following code:

    public static IHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> html, Expression<Func<TModel, TEnum>> expression, object htmlAttribute)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);

        var enumType = Nullable.GetUnderlyingType(metadata.ModelType) ?? metadata.ModelType;

        var enumValues = Enum.GetValues(enumType).Cast<object>();

        var items = from enumValue in enumValues
                    select new SelectListItem
                    {
                        Text = enumValue.ToString(),
                        Value = ((int)enumValue).ToString(),
                        Selected = enumValue.Equals(metadata.Model)
                    };
        return html.DropDownListFor(expression, items, string.Empty, htmlAttribute);
    }

I call this helper in two diffrent cases:

@EnumHelper.EnumDropDownListFor(Html, model => model.Part.Option, new { @class = "form-control checkpoint-choice toggle-comment" })

@EnumHelper.EnumDropDownListFor(Html, model => model.Part.ReviewGates[iRG].Option, new { @class = "form-control checkpoint-choice toggle-comment" })

Each call reference to the same enum. The binding works on both examples if i change the value and save it. But only the second example will select the default value or the saved value after loading the website. Both example are on the same website, an mvc create site. The model is binding as following:

@model presta.APQP.Base.ViewModels.UIPart

When i check the return value from my HtmlHelper class i can see that one item from items has set property Selected to true, but the html.DropDownListfor generate html code with no selected option.

Any idea?

thanks for any help...

0

There are 0 answers