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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Greg B
  • 14,597
  • 18
  • 87
  • 141

1 Answers1

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.

Dima
  • 6,721
  • 4
  • 24
  • 43
  • 3
    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. – Thorkil Holm-Jacobsen Apr 14 '15 at 11:53
  • This. Other answers to similar questions involve rolling your own string concatenation to build up the name. – Phil Cooper Sep 09 '17 at 07:52