Search code examples
c#asp.netasp.net-mvceditorforeditorformodel

How to get rid of default label in EditorForModel


I have an ASP.Net MVC project that I'm working on and I have a model that I want to turn into I form. I want to use EditorForModel() for this because I want it to automatically add fields to the form if I decide to add/remove properties to the model later.

The problem I'm having is that editor for model takes each property and creates the following HTML: (this is just generic. not the actual code)

<div class="editor-label"><label>Label Title</label></div>
<div class="editor-field"><input type="type"/></div

However what I want it do do for each field is this:

<div class="editor-field">
    <label>Label Title</label>
    <input type="type"/>
</div>

But if I try to do this in an editor template I get this instead:

<div class="editor-label"><label>Label Title</label></div>
<div class="editor-field">
    <label>Label Title</label>
    <input type="type"/>
</div>

How can I get EditorForModel() to not make it's own label field? I know I could always style it as hidden in CSS but it'd be nice if it wasn't even there to begin with so I could limit code confusion.

Thanks in advance.

PS: I've also tried using [HiddenInput(DisplayValue = false)] but this just hides the entire field and not just the label.


Solution

  • You need to write this in your editor template cshtml to get it work as expected:

    @foreach (var property in ViewData.ModelMetadata.Properties)
    {
        <div class="editor-field">
            <label>@property.GetDisplayName()</label>
            @Html.Editor(property.PropertyName)
        </div>
    }