I asked a question and got a great answer for my specific problem, but have run into a problem with <select>
lists using <label>
and trying to style the DataAnnotation Attribute [Display(Name="Text")]
with something like [Display(Name="Text <span class=\"myclass\">Special styled text</span>.")]
.
Here is the Question/Answer link.
The answer explained about Html Encoding and presented me with a solution for the Html.LabelFor
helper. It worked perfectly for my immediate situation. However, I later discovered that since I am using code to create <select>
lists, the new helper is not being picked up by it. Any help is greatly appreciated. Here is the <select>
builder code I am using:
public MvcHtmlString BuildInput(string fieldName,
SelectListItem item, string inputType)
{
var id = ViewData.TemplateInfo.GetFullHtmlFieldId(item.Value);
var wrapper = new TagBuilder("div");
wrapper.AddCssClass("selector-item");
var input = new TagBuilder("input");
input.MergeAttribute("type", inputType);
input.MergeAttribute("name", fieldName);
input.MergeAttribute("value", item.Value);
input.MergeAttribute("id", id);
input.MergeAttributes(Html.GetUnobtrusiveValidationAttributes
(fieldName, ViewData.ModelMetadata));
if(item.Selected)
input.MergeAttribute("checked", "checked");
wrapper.InnerHtml += input.ToString(TagRenderMode.SelfClosing);
var label = new TagBuilder("label"); // tried merging code around
// here but got it all wrong
label.MergeAttribute("for", id);
label.SetInnerText(item.Text);
wrapper.InnerHtml += label;
return new MvcHtmlString(wrapper.ToString());
}
As I indicated in the code I played around with trying to merge the helper code but could not get it right.
Again, any help is appreciated.