编码解码html <a> tag in mvc</a>

时间:2014-01-27 12:59:42

标签: html asp.net-mvc encoding

当我输入评论时,我有评论框,如果评论有任何链接,那么我会按照以下方式自动转换为链接。

protected string 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 txt;
        }

当我把标签显示为这样 “lt; a href ='http://asd.com'gt; http://asd.com lt; / a gt;”[现在我删除了&amp;否则它会在我的问题中创建链接。 ]

2 个答案:

答案 0 :(得分:1)

使用@Html.Raw方法打印此方法的输出。此方法呈现未编码的HTML。更多关于MSDN

您可以在此处找到示例:http://www.arrangeactassert.com/using-html-raw-in-asp-net-mvc-razor-views/

答案 1 :(得分:0)

+1以前的答案。 您也可以使用HtmlString类型

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);
        }