在MVC Razor视图中的@ Html.EditorFor中将自定义数据属性添加到html <option>标记</option>

时间:2012-05-21 10:41:04

标签: asp.net-mvc-3 razor

我想为我的选择列表中的每个选项添加一个自定义数据属性,我可以使用jQuery.data()或.attr()来实现。

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

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

有没有办法在EditorFor的新{}方法中执行此操作?

2 个答案:

答案 0 :(得分:4)

我将尝试使用下面描述的两种方法中的任何一种,

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

假设我们希望将MyModel数组显示为下拉列表,并将属性SomeProperty1SomeProperty2显示为&lt <中的数据属性;选项&gt; 元素。

    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>

<强> 2。使用templated razor delegates

    public static class RazorExtensions
    {
      public static HelperResult List<T>(this IEnumerable<T> items,
        Func<T, HelperResult> template)
      {
        return new HelperResult(writer =>
        {
          foreach (var item in items)
          {
            template(item).WriteTo(writer);
          }
        });
      }
    }

  // Model is MyModel[]
  <select>
  @Model.List(@<option name="@item.Id" data-attr-1="@item.SomeProperty1" data-attr-2="@item.SomeProperty2">@item.Value</option>)
  </select>

答案 1 :(得分:0)

我认为您可能需要拥有自己的编辑器扩展程序才能执行此操作。

相关问题