I fixed by explicitly setting the template in Object.cshtml
@Html.Editor(prop.PropertyName, prop.TemplateHint ?? prop.DataTypeName)
Still not clear why it previously worked in one view but not the other though.
题
I'm trying to implement some custom EditorTemplates but they're only being rendered by my Create view, and not the Edit one.
Model
public class Page {
public int PageID { get; set; }
[DataType(DataType.Html)]
[AllowHtml]
// I tried including [UIHint("Html")] but this made no difference
public string Content { get; set; }
...
}
/Views/Shared/EditorTemplates/Html.cshtml
@model string
@Html.TextArea("", Model, new { @class = "html"})
/Views/Shared/EditorTemplates/Object.cshtml
@if (ViewData.TemplateInfo.TemplateDepth > 1)
{
@ViewData.ModelMetadata.SimpleDisplayText
} else {
@Html.ValidationSummary(false)
foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForEdit
&& !ViewData.TemplateInfo.Visited(pm)))
{
if (prop.HideSurroundingHtml) {
@Html.Editor(prop.PropertyName)
@prop.DataTypeName
} else {
<div class="form-field">
@if (!String.IsNullOrEmpty(Html.Label(prop.PropertyName).ToHtmlString())) {
@Html.Label(prop.PropertyName)
}
@Html.Editor(prop.PropertyName)
</div>
}
}
}
/Views/Page/Create.cshtml ( This correctly renders Html.cshtml
)
@model MvcDisplayTemplates.Models.Page
@using (Html.BeginForm()) {
@Html.EditorForModel(Model)
<p><input type="submit" value="Create" /></p>
}
/Views/Page/Edit.cshtml ( This simply renders the default single line text editor )
@model MvcDisplayTemplates.Models.Page
@using (Html.BeginForm()) {
@Html.EditorForModel(Model)
<p><input type="submit" value="Save" /></p>
}
Interestingly, if I use EditorFor
on Edit.cshtml
then Html.cshtml
is actually rendered. e.g.
@Html.EditorFor(model => model.Content)
UPDATE: If I delete object.cshtml
then Html.cshtml
is also rendered correctly. So this does seem to be an issue in Object.cshtml
. It just seems odd that it works on one view but not another
解决方案
I fixed by explicitly setting the template in Object.cshtml
@Html.Editor(prop.PropertyName, prop.TemplateHint ?? prop.DataTypeName)
Still not clear why it previously worked in one view but not the other though.