Search code examples
c#htmlattributeshtml-helpercustom-data-attribute

Optional Data Attributes on Input [Html]


Is there a way to have an optional data attribute i.e data_val_required or required on an input/select?

@Html.DropDownListFor(x => x.PositionId, Model.Positions, new
{
    CurrentInput.Required ? data_val_required = "Please select a position" : noAttribute
})

My current scenario is that the dropdown lists are in a for loop which have a required property. So some of the inputs require a value while others dont. The only way I can think of doing it is wrapping the Html.DropDownListFor in a if statement that checks if the input is to be required and ouputs the correct html but thats code duplication.


Solution

  • I created an extension of object to add these properties to the htmlAttributes object. The extension of accepts a list of Item which is a custom class that has a Name and Key property. Then I use this to add the properties that I need for certain Inputs.

    public static IDictionary<string, object> AddProperties(this object obj, List<Item> properties)
    {
        var dictionary = obj.ToDictionary();
        properties.ForEach(x => dictionary.Add(x.Name, x.Vale));
        return dictionary;
    }