ASP.NET MVC editor template for property
- by Idsa
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?