Question

Following Brad Wilson's excellent series on using and customizing editor templates, I tried adding an Object.cshtml to the Shared\EditorTemplates folder. The template renders, but the [HiddenInput(DisplayValue = false)] on a model property doesn't render a hidden <input type="hidden" ... /> as expected. Using [HiddenInput(DisplayValue = true)] renders both the hidden and visible elements as expected.

I have verified that the default template for Object works fine and renders the hidden inputs. It's only a problem when building a custom template based on Brad's series above.

Était-ce utile?

La solution

Looks like something has changed. Inspecting the MVC 3 source, I found that prop.HideSurroundingHtml is used to determine when to print the surrounding HTML, not to print only the hidden element. The following template allows several levels of rendering an editor for an object graph:

@if (ViewData.TemplateInfo.TemplateDepth > 2)
{
    @(ViewData.ModelMetadata.Model != null ?
        ViewData.ModelMetadata.SimpleDisplayText :
        ViewData.ModelMetadata.NullDisplayText)
}
else
{
    foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm => pm.ShowForEdit && !ViewData.TemplateInfo.Visited(pm)))
    {
        if (!prop.HideSurroundingHtml)
        {
            if (!String.IsNullOrEmpty(Html.Label(prop.PropertyName).ToHtmlString()))
            {
                <div class="editor-label">@Html.Label(prop.PropertyName)</div>
            }
            @Html.Raw("<div class=\"editor-field\">")
        }
        @Html.Editor(prop.PropertyName)
        if (!prop.HideSurroundingHtml)
        {
            @Html.ValidationMessage(prop.PropertyName, "*")
            @Html.Raw("</div>")
        }
    }
}

Autres conseils

I tidied my version of that up a bit for anyone who cares:

@foreach (var modelMetadata in ViewData.ModelMetadata.Properties)
{
    if (modelMetadata.HideSurroundingHtml == false)
    {
        if (!string.IsNullOrEmpty(Html.Label(modelMetadata.PropertyName).ToHtmlString()))
        {
            <div class="editor-label">
                @Html.Label(modelMetadata.PropertyName)
            </div>
        }

        <div class="editor-field">
            @Html.Editor(modelMetadata.PropertyName)
        </div>
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top