0

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.

Bad Dub
  • 1,503
  • 2
  • 22
  • 52
  • Why don't use [Data Annotation](https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-6)? – Salah Akbari Oct 04 '18 at 14:25
  • The code Im current doing is a lot more complicated than this scenario and Data Annotations wont work. – Bad Dub Oct 04 '18 at 14:26

1 Answers1

0

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;
}
Bad Dub
  • 1,503
  • 2
  • 22
  • 52