我怎么能在我MVC3自定义编辑模板获得属性名 [英] How can I get the property name in my MVC3 custom Editor Template
问题描述
我在我的项目的枚举,我已经创建了此枚举自定义编辑器模板。所以,现在任何型号我有一个类型此枚举的属性,将呈现一个下拉。
I have an enumeration in my project and I've created a custom editor template for this enumeration. So, now any model I have with a property with a type of this enumeration, will render a drop down.
这个伟大的工程,但我想我的名字我的下拉与属性的名称的选择元素。这里是我的剃须刀code为我的编辑模板。
This works great, but I would like to name my select element of my dropdown with the name of the property. Here is my Razor code for my editor template.
@model ItemEnumerations.ItemType
<select id="PropertyNameHere" name="PropertyNameHere">
@foreach (ItemEnumerations.ItemType in Enum.GetValues(typeof(ItemEnumerations.ItemType))) {
<option value="@value" @(Model == @value ? "selected=\"selected\"" : "")>@value.ToString()</option>
}
</select>
所以,我在那里有'PropertyNameHere'为选择元素id和name属性,我想有我的模型的属性的名称。下面是一个例子:
So, where I have 'PropertyNameHere' for the select elements id and name attributes, I would like to have the name of the property of my model. Here is an example:
我的模型:
public class MyModel{
public int ItemID {get;set;}
public string ItemName {get;set;}
public ItemEnumerations.ItemType MyItemType {get;set;}
}
我查看code:
My View Code:
@model MyModel
@Html.LabelFor(m => model.ItemID)
@Html.DisplayForm(m => model.ItemID)
@Html.LabelFor(m => model.ItemName)
@Html.EditorFor(m => model.ItemName)
@Html.LabelFor(m => model.MyItemType )
@Html.EditorFor(m => model.MyItemType )
我想我的选择元素有MyItemType名称和标识。
I would like my select element to have a name and id of 'MyItemType'.
推荐答案
我发现了一本书,我这里有答案。事实上,它让我接近,但我可以再根据我发现谷歌的其余部分。
I found the answer in a book I have here. Actually, it got me close, but I then could google the rest based on what I found.
这是我需要的东西添加到我的编辑模板。
Here is what I needed to add to my editor template.
@{var fieldName = ViewData.TemplateInfo.HtmlFieldPrefix;}
<select id="@fieldName" name="@fieldName">
这篇关于我怎么能在我MVC3自定义编辑模板获得属性名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!