ASP.NET MVC editor template for property

Posted by Idsa on Stack Overflow See other posts from Stack Overflow or by Idsa
Published on 2012-08-30T07:48:11Z Indexed on 2012/09/06 9:38 UTC
Read the original article Hit count: 248

Usually I render my forms by @Html.RenderModel, but this time I have a complex rendering logic and I render it manually. I decided to create a editor template for one property. Here is the code (copy pasted from default object editor template implementation):

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<% var modelMetadata = ViewData.ModelMetadata; %>
<% if (modelMetadata.HideSurroundingHtml) { %>
    <%= Html.Editor(modelMetadata.PropertyName) %>
<% } else { %>
    <% 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) %>
        <%= Html.ValidationMessage(modelMetadata.PropertyName) %>
    </div>
<% } %>

And here is how I use it:

@Html.EditorFor(x => x.SomeProperty, "Property") //"Property" is template above

But it didn't work: labels are rendered regardless of DisplayName and editors are not rendered at all (in Watches Html.Editor(modelMetadata.PropertyName shows empty string). What am I doing wrong?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about asp.net-mvc