如何在EditorTemplate中获得完全限定的成员名称? [英] How do I get the fully qualified member name in an EditorTemplate?

查看:122
本文介绍了如何在EditorTemplate中获得完全限定的成员名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC 4网站,我正在将嵌套属性传递给EditorTemplate并使用ViewData.ModelMetadata.PropertyName构建字段名称,但是,这将获得子属性的属性名称,而不是完整的点符号名称我正在编辑的属性.

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:

给出以下类型

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>

_ImageUploader.cshtml编辑器模板如下

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>

渲染的HTML看起来像这样

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>

第5行和第6行的通知,在我称为ViewData.ModelMetadata.PropertyName的地方,我仅获得子属性名称"ImageUrl",但我想要"Entity.ImageUrl".如何获得这个完全合格的名称?

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?

推荐答案

使用@Html.NameFor(model => model)/@Html.NameForModel()代替ViewData.ModelMetadata.PropertyName,此方法应为您提供所需的名称.它是 Mvc3Futures 程序包的一部分,并已添加到MVC4.

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.

这篇关于如何在EditorTemplate中获得完全限定的成员名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆