我有一个自定义模板~/Views/Shared/EditorTemplate/String.cshtml
,它似乎导致异常:
The model item passed into the dictionary is of type 'Proj.Models.EnumType', but this dictionary requires a model item of type 'System.String'.
似乎只发生在Enums
。如果我删除模板,它也会消失。模板似乎没有引起它,我认为它甚至没有这么做。我可以把任何东西放在那里,异常是一样的。
所以......如果我有一个@Html.EditorFor
,我可以不使用model
enum
custom template
吗?
某些背景信息:
型号:
namespace Proj.Models
{
public enum EnumType
{
A = 0,
B = 1,
C = 2,
}
public class Mod
{
[Required]
public String Name;
[Required]
public EnumType Letter;
}
}
查看:
@model Proj.Models.Mod
@Html.EditorFor(m=>m) // Exception happens here
答案 0 :(得分:1)
以下是我发现为我工作的内容。
在模板中,请确保将模型声明为可为空的枚举类型。然后,在代码中,检查它是否具有值并基于该值进行适当的格式化。
@inherits System.Web.Mvc.WebViewPage<Proj.Models.EnumType?>
@{
Proj.Models.EnumType v = Model.HasValue ? Model.Value : {*some-default-value*};
@Html.{*Your-formatter-here*};
}