Bold text in Html.FormatValue using Razor

I want to get the following result. Username must be in bold:

Blabla Username Bla.

I have a format in a ressource file:

Blabla {0} Bla.

And in the view, I do the following:

@Html.FormatValue(User.Identity.Name, Resources.MyFormatString)

How can I make the username bold and use Html.FormatValue? Or is there another way to achieve this?

+4
source share
2 answers

You can simply change your resource so that it contains a bold tag, strong tag, or style.

how "Blabla <b>{0}</b> Bla.".

[]
, Html.FormatValue , , , -, :)

@Html.Raw string.Format .

@Html.Raw(string.Format(Resources.MyFormatString, "SomeName"))

( MVC 5, @Html.Raw 4)

: HTML , , , .
[/]

+6

html-, html- html-.

@(Resources.MyFormatString.FormatWithHtml(
    "<b>" + HttpUtility.HtmlEncode(User.Identity.Name) + "</b>"))

FormatWithHtml

/// Encodes to MvcHtmlString and includes HTML tags or already encoded strings, placeholder is the '|' character
public static MvcHtmlString FormatWithHtml (this string format, params string[] htmlIncludes) 
{
    var result = new StringBuilder();
    int i = -1;
    foreach(string part in format.Split('|')) {
        result.Append(HttpUtility.HtmlEncode(part));
        if (++i < htmlIncludes.Length)
            result.Append(htmlIncludes[i]);
    }
    return new MvcHtmlString(result.ToString());
}

:

@("Resource is safe to html characters <&> and will include |format tags| or any | user input."
    .FormatWithHtml("<b>", "</b>", "<b id='FromUser'>" +HttpUtility.HtmlEncode("<a href='crack.me'>click</a>") +"</b>"))

html < & → < a href= 'crack.me' > click </a> .

+2

Source: https://habr.com/ru/post/1544708/


All Articles