How do I get the fully qualified member name in an EditorTemplate?
Asked Answered
A

1

4

I have an ASP.NET MVC 4 site and I am passing a nested property to an EditorTemplate and building the field name using ViewData.ModelMetadata.PropertyName however, this gets the property name of the child property, not the full dot-notation name of the property I'm editing.

An example will illustrate best:

Given the following types

public class EditEntityViewModel
{
     // elided
     public Entity Entity { get; set}
}


public class Entity 
{
    // elided
    public string ImageUrl { get; set; }
}

My Edit and Create views are as follows:

@model EditEntityViewModel

<div>
    @Html.EditorFor(model => model.Entity.ImageUrl , "_ImageUploader")
</div>

The _ImageUploader.cshtml Editor Template is as follows

@model System.String

<div class="uploader">
    @Html.LabelFor(model => model)
    @Html.HiddenFor(model => model)
    <div data-rel="@(ViewData.ModelMetadata.PropertyName)">   
        <input type="file" name="@(ViewData.ModelMetadata.PropertyName)Upload" />
    </div>
</div>

The rendered HTML looks like this

<div>
   <div class="uploader">
        <label for="Entity_ImageUrl">Image</label>
        <input id="Entity_ImageUrl" name="Entity.ImageUrl" type="hidden"/>
        <div data-rel="ImageUrl"> <!-- Problem -->
             <input type="file" name="ImageUrlUpload" /><!-- Problem -->
        </div>
    </div>
</div>

Notice on line 5 and 6, where I've called ViewData.ModelMetadata.PropertyName, I'm only getting the child property name "ImageUrl" but I want "Entity.ImageUrl". How do get get this fully qualified name?

Ascetic answered 27/3, 2013 at 8:43 Comment(1)
Are you using MVC3 or MVC4?Helmet
I
10

Use @Html.NameFor(model => model) / @Html.NameForModel() instead of ViewData.ModelMetadata.PropertyName, this method should give you desired name. It's part of Mvc3Futures package and was added to MVC4.

Incorporate answered 27/3, 2013 at 9:15 Comment(2)
Note: The id attributes of the elements replace . with _, so if you want to reference the id (for instance with jQuery) you can use @Html.IdForModel() instead.Chemosh
This. Other answers to similar questions involve rolling your own string concatenation to build up the name.Marcusmarcy

© 2022 - 2024 — McMap. All rights reserved.