asp.net-mvc-2editorforeditorformodel

EditorFor Template for boolean type


How can we access the model's property name when using EditorFor() with a template for value types, for instance like the one below for bool type?

It seems that the MVC somehow pulls out the property name because it correctly renders the checkbox (or textbox, if used) with the correct property name, but where does MVC get it?

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<bool>" %>
 <fieldset>
        <legend>insert boolean property name here or the value of DisplayName attribute??</legend>
            <div class="clear">
                <p>
                    <%: Html.CheckBox("", Model) %>
                    <span>insert boolean property name here or the value of DisplayName attribute??</span>
                </p>
            </div>
    </fieldset>

Solution

  • <%: ViewData.ModelMetadata.PropertyName %>
    

    or:

    <%: ViewData.ModelMetadata.DisplayName %>
    

    UPDATE:

    Example of resource localized display attribute:

    public class LocalizedDisplayNameAttribute : DisplayNameAttribute
    {
        public LocalizedDisplayNameAttribute(string name)
            : base(GetValueFromResource(name))
        { }
    
        private static string GetValueFromResource(string name)
        {
            // TODO: fetch the display name from wherever you want
            throw new NotImplementedException();
        }
    }