传递到字典中的编辑器模板(单选按钮列表)和模型项的类型为[enum],但字典需要模型类型X



四处寻找类似的标题,但都没有切中要害,或者什么都没用。我理解我为什么会出现错误,我只是想知道如何使用EditorForModel来修复它。我得到这个错误:

传递到字典中的模型项的类型为"MyNameSpace.ViewModels.MyData+MyEnum",但是字典需要类型为的模型项"MyNameSpace.ViewModels.MyData".

我的型号:

    [UIHint("MyRadioButton")]
    public MyEnum MyRadioRadioButton { get; set; }
    //
    //
    public enum MyEnum
    {
        Choice1,
        Choice2            
    }

我正在使用[UIHint]调用一个名为MyRadioButton.cshtml的EditorTemplate。现在,我的视图也在使用@Html.EditorForModel调用EditorTemplate。这是视图页面中调用通用模板的部分:

@Html.EditorForModel("BasicDetails")

这两个模板都在"/Shared/EditorTemplates/"文件夹中。

这是MyRadioButton.cshtml模板:

<td>
    <div class="radio">
        @Html.RadioButtonFor(m => m.MyRadioButton, "Choice1")<br />
        @Html.RadioButtonFor(m => m.MyRadioButton, "Choice2")
    </div>
</td>

这就是BasicDetails.cshtml(由上面的@Html.EditorForModel调用):

@using MyNameSpace.ViewModels
@model MyData
<table>
    @Html.EditorFor(x => x.FirstName)
    @Html.EditorFor(x => x.LastName)
    @Html.EditorFor(x => x.MyRadioButton) //This is where my error is thrown
</table>

我想避免上面的单选按钮列表编辑器模板中出现任何复杂的内容,因为其中还有其他内容(我去掉了所有多余的内容,但仍然会出现错误)。我在不同的视图中多次使用特定的单选按钮列表(这就是为什么我想用模板而不是复制/粘贴它)。有什么建议吗?

从BasicDetails.cshtml调用EditorFor作为@Html.EditorFor(x => x.MyRadioButton)

这意味着传递给EditorFor的模型类型是Enum类型。

但是在EditorFor Template(MyRadioButton.cs.html)中,我认为您已经使用了该类作为模型。错误也是如此。

因此,我们需要将MyRadioButton.cshtml中的模型类型更改为MySenu(带命名空间)

将相同的模型传递给编辑器对于模板@Html.EditorFor(x=>x,"MyRadioButton")

目前,我只是简单地依靠EditorForModel/EditorTemplates/中提取模板,而不是将[UIHint]用于单选按钮列表,我只是在该模板中插入@Html.RadioButtonFor组。这对我很有用,可以最大限度地减少复制/粘贴。

在某个时候,我必须学会停止使用template>for a template>for an template范型,并知道什么时候适可而止。:)

最新更新