我使用DropDownListFor的模板化帮助程序无法反映枚举的模型.为什么? [英] My templated helper using a DropDownListFor does NOT reflect the model of enum. Why?

查看:67
本文介绍了我使用DropDownListFor的模板化帮助程序无法反映枚举的模型.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型如下:

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的模板化帮助程序无法反映枚举的模型.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆