Asp.net mvc 3 将自定义数据属性添加到html<;选项>;MVC Razor视图中@Html.EditorFor内的标记

Asp.net mvc 3 将自定义数据属性添加到html<;选项>;MVC Razor视图中@Html.EditorFor内的标记,asp.net-mvc-3,razor,Asp.net Mvc 3,Razor,我想向selectlist中的每个选项添加一个自定义数据属性,这可以通过jQuery.data()或.attr()实现 但是,我正在使用以下html帮助程序设置我的选择列表: @Html.EditorFor(x => x.MySelect, MVC.Shared.Views.EditorTemplates.KeyValuePairSelectList, new { SelectListOptions = Model.MySelectList}) 在EditorFor的新{}方法中有什么方

我想向selectlist中的每个选项添加一个自定义数据属性,这可以通过jQuery.data()或.attr()实现

但是,我正在使用以下html帮助程序设置我的选择列表:

@Html.EditorFor(x => x.MySelect, MVC.Shared.Views.EditorTemplates.KeyValuePairSelectList, new { SelectListOptions = Model.MySelectList})

在EditorFor的新{}方法中有什么方法可以做到这一点吗?

我认为您可能需要有自己的编辑器扩展才能做到这一点。

我认为您可能需要有自己的编辑器扩展才能做到这一点。

我将尝试使用以下两种方法中的任何一种

1。使用自定义编辑器模板

假设我们希望将
MyModel
数组显示为下拉列表,并且属性
SomeProperty1
SomeProperty2
将在元素中显示为数据属性

    public class MyModel
    {
      public int Id { get; set; }
      public string Value { get; set; }
      public string SomeProperty1 { get; set; }
      public string SomeProperty2 { get; set; }
    }

  // CustomSelectList.cshtml (editor template)
  @model MyModel[]

  <select>
  @foreach (var i in Model)
  {
    <option name="@i.Id" data-attr-1="@i.SomeProperty1" data-attr-2="@i.SomeProperty2">@i.Value</option>
  }
  </select>
公共类MyModel
{
公共int Id{get;set;}
公共字符串值{get;set;}
公共字符串SomeProperty1{get;set;}
公共字符串SomeProperty2{get;set;}
}
//CustomSelectList.cshtml(编辑器模板)
@模型MyModel[]
@foreach(模型中的var i)
{
@i、 价值观
}
2。使用

公共静态类RazorExtensions
{
public static HelperResult列表(此列表为IEnumerable items,
Func(模板)
{
返回新的HelperResult(writer=>
{
foreach(项目中的var项目)
{
模板(项目).WriteTo(编写器);
}
});
}
}
//模型是MyModel[]
@Model.List(@@item.Value)

我将尝试使用以下两种方法中的任何一种

1。使用自定义编辑器模板

假设我们希望将
MyModel
数组显示为下拉列表,并且属性
SomeProperty1
SomeProperty2
将在元素中显示为数据属性

    public class MyModel
    {
      public int Id { get; set; }
      public string Value { get; set; }
      public string SomeProperty1 { get; set; }
      public string SomeProperty2 { get; set; }
    }

  // CustomSelectList.cshtml (editor template)
  @model MyModel[]

  <select>
  @foreach (var i in Model)
  {
    <option name="@i.Id" data-attr-1="@i.SomeProperty1" data-attr-2="@i.SomeProperty2">@i.Value</option>
  }
  </select>
公共类MyModel
{
公共int Id{get;set;}
公共字符串值{get;set;}
公共字符串SomeProperty1{get;set;}
公共字符串SomeProperty2{get;set;}
}
//CustomSelectList.cshtml(编辑器模板)
@模型MyModel[]
@foreach(模型中的var i)
{
@i、 价值观
}
2。使用

公共静态类RazorExtensions
{
public static HelperResult列表(此列表为IEnumerable items,
Func(模板)
{
返回新的HelperResult(writer=>
{
foreach(项目中的var项目)
{
模板(项目).WriteTo(编写器);
}
});
}
}
//模型是MyModel[]
@Model.List(@@item.Value)