开发者

Html.Encode and string containing html snippets

I'm trying to highlight the result of a search within some text. I have written an extension method:

public static string Highlight(this HtmlHelper html, string input, string searchPhrase)
{
    Regex.Replace(input, 
                  "\\b" + searchPhrase + "\\b", 
                  "<strong>" + searchPhrase + "</strong>", 
                  RegexOptions.IgnoreCase);
}

But obvisouly when this is Html.Encoded from the view, the html tags are just rendered as part of the text.

Is there a better way of doing this? Or if my idea is ok, how do I make 开发者_StackOverflow中文版it work?


public static MvcHtmlString Highlight(this HtmlHelper html, string input, string searchPhrase)
{
    var value = Regex.Replace(
        input, 
        "\\b" + searchPhrase + "\\b", 
        "<strong>" + searchPhrase + "</strong>", 
        RegexOptions.IgnoreCase
    );
    return MvcHtmlString.Create(value);
}

and in the view:

@Html.Highlight("foo", "f")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜