I have a couple of custom data annotations available to my editing ViewModels.
Because they can apply to any type of form control, I test for them in every EditorTemplate
.
Can anybody recommend a way to reuse shared view code like this in MVC?
I'm considering a HtmlHelper or an AppCode/Helper class. Not sure which is best if either, I'm a bit of a newb with both.
@{
var htmlAttributesFromView = ViewData["htmlAttributes"] ?? new { };
var htmlAttributes = Html.MergeHtmlAttributes(htmlAttributesFromView, new { @class = "form-control" });
bool isDisplayInfoOnIconClickAttribute = false;
string title = "";
string description = "";
var infoOnClickAttributes = (ViewData.ModelMetadata).ContainerType.GetProperty(ViewData.ModelMetadata.PropertyName).GetCustomAttributes(typeof(DisplayInfoOnIconClickAttribute), false);
if (infoOnClickAttributes.Length > 0)
{
DisplayInfoOnIconClickAttribute attribute = infoOnClickAttributes[0] as DisplayInfoOnIconClickAttribute;
isDisplayInfoOnIconClickAttribute = true;
title = attribute.Title;
description = attribute.Description;
}
bool isDisplayTextInfoAttribute = false;
string info = "";
var textInfoAttributes = (ViewData.ModelMetadata).ContainerType.GetProperty(ViewData.ModelMetadata.PropertyName).GetCustomAttributes(typeof(DisplayTextInfoAttribute), false);
if (textInfoAttributes.Length > 0)
{
DisplayTextInfoAttribute attribute = textInfoAttributes[0] as DisplayTextInfoAttribute;
isDisplayTextInfoAttribute = true;
info = attribute.Info;
}
}
<div class="form-group">
@Html.LabelFor(model => model, htmlAttributes: new { @class = "control-label col-md-3 text-right-md" })
<div class="col-md-8">
@Html.TextBoxFor(model => model, htmlAttributes)
@Html.ValidationMessageFor(model => model)
</div>
<a class="infoonclick col-md-1" title="@Html.DisplayNameFor(model => model)" data-content="@Html.DescriptionFor(model => model)">
<span class="fa fa-info-circle"></span>
</a>
</div>