Encode Decode html tag in mvc

2019-09-18 20:35发布

问题:

I have comment box when i type the comment and if comment have any link then i automatically convert to the link by following way.

protected string MakeLink(string txt)
        {
            Regex regx = new Regex("(http|https)://([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);

            MatchCollection mactches = regx.Matches(txt);

            foreach (Match match in mactches)
            {
                txt = txt.Replace(match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>");
            }

            return txt;
        }

when i put the tag will show like this " lt;a href='http://asd.com'gt;http://asd.com lt;/a gt; " [ right now i removed & otherwise it create link in my Question. ]

回答1:

Use @Html.Raw method to print output of this method. This method renders unencoded HTML. More on MSDN

The example you can find here: http://www.arrangeactassert.com/using-html-raw-in-asp-net-mvc-razor-views/



回答2:

+1 for previous answer. Also you can use HtmlString type

protected HtmlString MakeLink(string txt)
        {
            Regex regx = new Regex("(http|https)://([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);

            MatchCollection mactches = regx.Matches(txt);

            foreach (Match match in mactches)
            {
                txt = txt.Replace(match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>");
            }

            return new HtmlString(txt);
        }