I am looking for some feedback on custom EditorTemplates I have created. The purpose of my custom EditorTemplates is to make sure that the Bootstrap 3 CSS class form-control
is always present, in addition to some appropriate HTML attributes depending on the data type of the view model's property.
However, I still want to be able to add additional CSS classes or various HTML attributes when actually using the EditorTemplate. For example, when I use
@Html.EditorFor(model => model.Something, new { htmlAttributes = new { @class = "datepicker" } })
I would expect to get HTML similar to this
<input type="text" class="datepicker form-control" id="Something" name="Something" />
I have my current code for my custom string
EditorTemplate below (other data types are of course similarly done). This works, but I am wondering if I have made it too complicated? Any feedback would be appreciated.
@{
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(ViewData["htmlAttributes"]);
if (!attributes.ContainsKey("placeholder") &&
!string.IsNullOrWhiteSpace(ViewData.ModelMetadata.Watermark))
{ attributes.Add("placeholder", ViewData.ModelMetadata.Watermark); }
if (!attributes.ContainsKey("aria-required") &&
ViewContext.ViewData.ModelMetadata.IsRequired)
{ attributes.Add("aria-required", "true"); }
// If the attributes dictionary already has a class attribute defined
if (attributes.ContainsKey("class"))
// Add the bootstrap class to it
{ attributes["class"] += " form-control"; }
else
// Create class attribute
{ attributes.Add("class", "form-control"); }
}
@Html.TextBox(string.Empty, ViewData.TemplateInfo.FormattedModelValue, attributes)