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

大憨熊 提交于 2019-12-06 05:43:38

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/15654716/how-do-i-get-the-the-fully-qualified-member-name-in-an-editortemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!