asp.net-mvc-3 – 如何在MVC3自定义编辑器模板中获取属性名称

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 如何在MVC3自定义编辑器模板中获取属性名称前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的项目中有一个枚举,我为这个枚举创建了一个自定义编辑器模板。所以,现在我有一个类型的这个枚举的属性,将渲染一个下拉列表。

这很好,但我想用属性名称命名我的下拉菜单中的select元素。这是我的编辑器模板的Razor代码

  1. @model ItemEnumerations.ItemType
  2.  
  3. <select id="PropertyNameHere" name="PropertyNameHere">
  4. @foreach (ItemEnumerations.ItemType in Enum.GetValues(typeof(ItemEnumerations.ItemType))) {
  5. <option value="@value" @(Model == @value ? "selected=\"selected\"" : "")>@value.ToString()</option>
  6. }
  7. </select>

所以,我选择元素id和name属性的“PropertyNameHere”,我想拥有我的模型的属性名称。这里是一个例子:

我的型号:

  1. public class MyModel{
  2. public int ItemID {get;set;}
  3. public string ItemName {get;set;}
  4. public ItemEnumerations.ItemType MyItemType {get;set;}
  5. }

我的查看代码

  1. @model MyModel
  2.  
  3. @Html.LabelFor(m => model.ItemID)
  4. @Html.DisplayForm(m => model.ItemID)
  5.  
  6. @Html.LabelFor(m => model.ItemName)
  7. @Html.EditorFor(m => model.ItemName)
  8.  
  9. @Html.LabelFor(m => model.MyItemType )
  10. @Html.EditorFor(m => model.MyItemType )

我想要我的select元素的名称和id为’MyItemType’。

解决方法

我在这里的一本书中找到了答案。其实这让我很近,但是我可以根据我发现的方式google其余的。

这是我需要添加到我的编辑器模板。

  1. @{var fieldName = ViewData.TemplateInfo.HtmlFieldPrefix;}
  2. <select id="@fieldName" name="@fieldName">

猜你在找的asp.Net相关文章