微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何为枚举创建EditorTemplate?

我有一个带枚举的模型

public enum Gender
{
    Male,Female,Unspecified
}

public class FooClass
{
    public Gender UserGender {set; get;}
}

由于此Gender可能在其他类中使用,我想为它创建一个EditorTemplate并在create / edit视图中请求编辑器:

@Html.EditorFor(model => model.UserGender)

之后,我创建了一个位于Views / Shared / EditorTemplates / Gender.cshtml中的局部视图.在模板中,我添加了一些仅用于测试的内容

@model TestProject.Models.Entity.Gender
@Html.TextBox("")

要么

@model TestProject.Models.Entity.Gender
Hello...

但我得到的只是一个例外:

The model item passed into the dictionary is null,but this dictionary requires a non-null model item of type ‘TestProject.Models.Entity.Gender’.

这是编辑器模板的工作原理还是我完全偏离轨道?

编辑:

如果我删除模板文件(Gender.cshtml),我将获得一个文本字段作为编辑器,并且不会抛出任何异常.

此外,这是一个创建视图,在控制器中我没有传递任何对象.我只是调用return View();

解决方法

你可以尝试这样的事情

@model Nullable<TestProject.Models.Entity.Gender>
@Html.ListBox("lb",Enum.GetValues(typeof(TestProject.Models.Entity.Gender)).Cast<TestProject.Models.Entity.Gender>().Select(i => new SelectListItem() { Text = i.ToString(),Value = i.ToString(),Selected=i==Model }))

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐