My templated helper using a DropDownListFor does N

2019-09-04 07:41发布

问题:

I have a model as follows:

namespace Q01.Models
{
    public enum Sex { Male, Female }

    public class Person
    {
        public string Name { get; set; }
        public Sex? Sex { get; set; }
    }
}

A utilities class to obtain a SelectList object to populate a DropDownListFor is defined as follows:

using System;
using System.Linq;
using System.Web.Mvc;

namespace Q01.Utilities
{
    public static class Utilities
    {
        public static SelectList EnumToSelectList<TEnum>(this TEnum? obj) where TEnum: struct
        {
            var values = from TEnum x in Enum.GetValues(typeof(TEnum))
                         select new { Value = x, Text = x };
            return new SelectList(values, "Value", "Text");
        }
    }
}

I create a templated helper named Sex.cshtml for the type of Sex as follows:

@using Q01.Utilities
@using Q01.Models
@model Sex?
@Html.DropDownListFor(x => x, Model.EnumToSelectList(), "--Select--")

In HomeController, I create an instance of Person and pass it to the view as follows:

using System.Web.Mvc;
using Q01.Models;

namespace Q01.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Create()
        {
            Person p = new Person();
            p.Sex = Sex.Female;
            return View(p);
        }
    }
}

And the corresponding view is declared as follows:

@using Q01.Utilities
@model Q01.Models.Person
@using (Html.BeginForm())
{
    <div>Using Sex.cshtml: @Html.EditorFor(x => x.Sex)</div>
    <div>Not using Sex.cshtml: @Html.DropDownListFor(x => x.Sex, Model.Sex.EnumToSelectList(), "--Select--")</div>
}

The screenshot of the output is shown as follows:

The question is: why the Sex.cshtml does not reflect the model? It should select Female rather than "--Select--".

回答1:

Add value to EnumToSelectList:

public static class Utilities
{
    public static SelectList EnumToSelectList<TEnum>(this TEnum? obj, object value) where TEnum: struct
    {
        var values = from TEnum x in Enum.GetValues(typeof(TEnum))
                     select new { Value = x, Text = x };
        return new SelectList(values, "Value", "Text", value);
    }
}

Then Model.EnumToSelectList(x.Sex). You just have to provide selected value in SelectList constructor.