0

I want to add a custom data attribute to each option in my selectlist, which I could achieve with jQuery.data() or .attr().

However, I am setting up my selectlists with the following html helper:

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

Is there a way to do it in the new{} method of the EditorFor?

2 Answers 2

4

I will try using any one of the two ways described below,

1. Using custom editor template

Suppose we want to display MyModel array as a dropdownlist and the properties SomeProperty1 and SomeProperty2 to be displayed as data attributes in the <option> element.

    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. Using 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>
Sign up to request clarification or add additional context in comments.

Comments

0

I think you may need to have your own editor extension to do this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.