以下列模型为例:
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; }
}
}
让我们说我们正在尝试添加我们的两个朋友,一个普通的朋友和一个时髦的朋友:
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>
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>
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>
在Hipster
EditorTemplate中,代码
@Html.EditorFor(model => model, "Person")
应该将Hipster
模型传递给Person
EditorTemplate,这样我就不必为共享属性(基类型Person
)重复模板化代码。 / p>
目前,上述代码完全忽略EditorFor
,只显示Hipster
特定属性(即CoolPoints
和HatPreference
)。
或者,我可以更改Create.cshtml中的以下代码:
@Html.EditorFor(model => model.NormalFriend)
@Html.EditorFor(model => model.HipsterFriend)
为:
@Html.EditorFor(model => model.NormalFriend)
@Html.EditorFor(model => model.HipsterFriend, "Person") //break convention and the idea of nesting
@Html.EditorFor(model => model.HipsterFriend)
这将实现我想要的,但似乎错误的是我无法在Hipster
EditorTemplate中执行此操作。
我的逻辑是否有缺陷还是我错过了什么?我认为可能因为害怕递归而无视这条线,但templateName
论证应该澄清。继承基类型和嵌套的这种想法适用于局部,但局部不能处理验证所必需的复杂对象的ViewData.TemplateInfo.GetFullHtmlFieldName
。
<小时/> 这个问题是相关的:In an Editor Template call another Editor Template with the same Model虽然解决方案不适用于我的情况。有没有使用部分来嵌套视图的解决方法,还是我唯一的方法?
答案 0 :(得分:-1)
嗯,问题不在于嵌套编辑。
&#34;模板只能用于字段访问,属性访问,单维数组索引或单参数自定义索引器表达式。&#34;