Trying to modify a builder to style text in DataAnnotation Attribute [Display(Name=“Text”)]

半世苍凉 提交于 2019-12-11 19:47:01

问题


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.


回答1:


Just replace:

label.SetInnerText(item.Text);

with:

label.InnerHtml = item.Text;


来源:https://stackoverflow.com/questions/9824252/trying-to-modify-a-builder-to-style-text-in-dataannotation-attribute-displayna

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!