1 Replies - 1240 Views - Last Post: 19 August 2018 - 08:56 PM Rate Topic: -----

#1 SchizoCoder   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 16-July 18

Add data attribute to option tag in ASP.NET MVC DropDownList

Posted 13 August 2018 - 09:26 AM

In my ASP.NET MVC form I want to have a drop down where each <option> tag has a boolean data attribute. This attribute determines whether the drop down should dynamically have a text box added next to it when the selected item has a "true" value for the data attribute.

I wasn't able to find a way to do this with the built in DropDownList helper, so I created an editor template:

@model SystemChangeForms.ViewModels.PartialViewModels.AffectedSystemPartialViewModel

@if (Model != null)
{
    <select name="@Html.NameFor(m => Model.AffectedSystemIds[Model.Count])" id="@Html.IdFor(m => Model.AffectedSystemIds)"
            class="form-control template-control affected-system-form-control" data-val="true" 
            data-val-required="The affected system field is required"
            data-other-field-type="2" data-other-field-name="AffectedSystem">
        <option value="">Select Affected System</option>
        @if (Model.AffectedSystems != null && Model.AffectedSystems.Count > 0)
        {
            foreach (var item in Model.AffectedSystems)
            {
                string selected = "";
                if (Model.AffectedSystemIds != null)
                {
                    selected = Model.AffectedSystemIds[Model.Count] == item.Id ? "selected" : "";
                }
                <option value="@item.Id" data-has-other-field="@item.HasOtherField" @selected>@item.Name</option>
            }
        }
        @{ Model.Count++; }
    </select>
}


It partially works; however, it doesn't have validation, and doesn't get the CSS class for invalid selection if someone doesn't choose anything. Because of this, I would prefer to use the built-in DropDownList, but I don't know if that's possible. It would be much easier than having to write my own control, with validation, and test it. Any suggestions?

Is This A Good Question/Topic? 0
  • +

Replies To: Add data attribute to option tag in ASP.NET MVC DropDownList

#2 SchizoCoder   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 16-July 18

Re: Add data attribute to option tag in ASP.NET MVC DropDownList

Posted 19 August 2018 - 08:56 PM

I decided to use the ASP.NET MVC open source code from GitHub:

https://github.com/A...ctExtensions.cs

I will add a data- attribute to the option tag by adding the necessary code. When I'm done I will post it here in case anyone's interested.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1