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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With