问题描述
我的模型如下:
namespace Q01.Models
{
public enum Sex { Male, Female }
public class Person
{
public string Name { get; set; }
public Sex? Sex { get; set; }
}
}
用于获取SelectList
对象以填充DropDownListFor
的实用程序类的定义如下:
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");
}
}
}
我为Sex
类型创建一个名为Sex.cshtml
的模板化助手,如下所示:
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--")
在HomeController
中,我创建一个Person
的实例,并将其传递给视图,如下所示:
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);
}
}
}
对应的视图声明如下:
@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>
}
输出的屏幕截图如下:
问题是:为什么Sex.cshtml
不能反映模型?应该选择Female
而不是"--Select-".
The question is: why the Sex.cshtml
does not reflect the model? It should select Female
rather than "--Select--".
推荐答案
为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);
}
}
然后Model.EnumToSelectList(x.Sex)
.您只需要在SelectList
构造函数中提供选定的值即可.
Then Model.EnumToSelectList(x.Sex)
. You just have to provide selected value in SelectList
constructor.
这篇关于我使用DropDownListFor的模板化帮助程序无法反映枚举的模型.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!