嵌套编辑器模板:无法将model => model传递给基本编辑器模板

Car*_*all 5 c# asp.net-mvc inheritance mvc-editor-templates

以下列模型为例:

namespace MyNamespace.Model
{
    //you can only have two friends for the sake of simplicity in this example :P
    public class Friends{
        public Person NormalFriend { get; set; }
        public Hipster HipsterFriend { get; set; }
    }

    public class Person{
        public string Name { get; set; }
        public string PhoneNumber { get; set; }
    }

    public class Hipster : Person
    {
        public HatType HatPreference { get; set; }
        public int CoolPoints { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

假设我们正在尝试添加我们的两个朋友,一个普通朋友和一个时髦朋友:

Create.cshtml:

@model MyNamespace.Model.Friends

<div class='container'>
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary(true)
        @Html.AntiForgeryToken()

        @Html.EditorFor(model => model.NormalFriend) //uses Person EditorTemplate by convention

        @Html.EditorFor(model => model.HipsterFriend) //uses Hipster EditorTemplate by convention
</div>
Run Code Online (Sandbox Code Playgroud)

EditorTemplates/Person.cshtml:

@model MyNamespace.Model.Person

<div class='row'>
    <div class='col'>
        @Html.EditorFor(model => model.Name)
    </div>
    <div class='col'>
        @Html.EditorFor(model => model.PhoneNumber)
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

EditorTemplates/Hipster.cshtml:

@model MyNamespace.Model.Hipster

@Html.EditorFor(model => model, "Person") // <-- what I've tried and it isn't working

<div class='row'>
    <div class='col'>
        @Html.EditorFor(model => model.CoolPoints)
    </div>
    <div class='col'>
        @Html.EditorFor(model => model.HatPreference)
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

HipsterEditorTemplate中,代码

@Html.EditorFor(model => model, "Person")
Run Code Online (Sandbox Code Playgroud)

应该将Hipster模型传递给PersonEditorTemplate,这样我就不必为共享属性(基本类型Person)重复模板化代码.

目前,上面的代码只是完全忽略了EditorFor,只显示了Hipster特定的属性(即CoolPointsHatPreference).

或者,我可以在Create.cshtml中更改以下代码:

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

 @Html.EditorFor(model => model.HipsterFriend) 
Run Code Online (Sandbox Code Playgroud)

至:

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

 @Html.EditorFor(model => model.HipsterFriend, "Person") //break convention and the idea of nesting     
 @Html.EditorFor(model => model.HipsterFriend) 
Run Code Online (Sandbox Code Playgroud)

这将实现我想要的,但似乎错误的是我无法在HipsterEditorTemplate中执行此操作.

我的逻辑是否有缺陷还是我错过了什么?我认为可能因为害怕递归而无视这条线,但templateName争论应该澄清.继承基类型和嵌套的这种想法适用于partials,但partials不处理ViewData.TemplateInfo.GetFullHtmlFieldName验证所必需的复杂对象.


这个问题是相关的:在编辑器模板中调用具有相同模型的另一个编辑器模板,尽管该解决方案不适用于我的情况.是否有一种解决方法来嵌套视图而不使用partials或者这是我的唯一方法?