I’ve created a MVC extension to auto apply attributes to html inputs. Which is all working as expected however if i want to add a css class to the html input and it already has a css class the code bombs as the attribute is already set.
Heres my code:
public static MvcHtmlString LockableTextBox(this HtmlHelper helper, string name, object value, object htmlAttributes, bool locked)
{
RouteValueDictionary dic = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (locked)
{
dic.Add("readonly", "readonly");
dic.Add("class", "field-locked");
}
return helper.TextBox(name, value, dic);
}
I call it like so:
@Html.LockableTextBox("Initals", Model.Initals, new {}, Model.Locked)
which works, but this call does not
@Html.LockableTextBox("Initals", Model.Initals, new {@Class="field"}, Model.Locked)
How do i change the dic.Add(“class”, “field-locked”) line so that it adds a my extra class to the existing class attribute?
You can use it like simple
Dictionary. Check if you have already such key and append your string to existing value, otherwise add new.