MVC 4 -字符串自定义模板与枚举混淆



我有一个自定义模板~/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。如果我移除模板,它也会消失。似乎不是模板造成的,我认为它甚至没有走到那么远。我可以在里面放任何东西,例外是一样的。

所以…如果我有custom template,我可以不使用@Html.EditorFormodelenum吗?

一些背景:

模型:

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

以下是我发现对我有用的方法。

模板中,确保将模型声明为可空枚举类型。然后,在代码中,检查它是否有一个值,并在此基础上进行适当的格式化。
@inherits System.Web.Mvc.WebViewPage<Proj.Models.EnumType?>
@{
    Proj.Models.EnumType v = Model.HasValue ? Model.Value : {*some-default-value*};
    @Html.{*Your-formatter-here*};            
}

最新更新