我在我的項目中有一個枚舉,並且爲此枚舉創建了一個自定義編輯器模板。所以,現在我有一個屬性與這種枚舉類型的任何模型,將呈現一個下拉。如何在我的MVC3自定義編輯器模板中獲取屬性名稱
這很好,但我想用屬性的名稱命名我的下拉列表中的select元素。這是我的編輯器模板的Razor代碼。
@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屬性,我想有我的模型的屬性的名稱。這裏有一個例子:
我的模型:
public class MyModel{
public int ItemID {get;set;}
public string ItemName {get;set;}
public ItemEnumerations.ItemType MyItemType {get;set;}
}
我查看代碼:
@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' 的名稱和ID。
在編輯器模板獲得屬性的名稱也許更好的解決辦法是延長DropDownFor方法來處理我的枚舉? –
試試這個...http://blog.nathan-taylor.net/2012/10/aspnet-mvc-get-field-name-and-id-for.html –