如何使用 Razor 语法获取指向 ASP.NET MVC 4 中文本中的 URL 的链接



我有一个带有文本字段的模型。文本可以包含多个 URL。它不必包含 URL,也没有特定的格式。

@Html.DisplayFor(model => model.TextWithSomeUrls)

当然,文本和URL的显示方式与普通文本相同。不过,我想将 URL 显示为有效的单个链接。ASP.NET/剃刀中有没有辅助方法?

编辑:现在输出是:

http://www.google.com, foo: bar;  http://www.yahoo.com

这正是文本字段的内容。

但是我想获取URL,

并且仅获取呈现为链接的URL,如下所示:

<a href="http://www.google.com">http://www.google.com</a>, foo: bar; <a href="http://www.yahoo.com">http://www.yahoo.com</a>

我的解决方案

public static partial class HtmlExtensions
{
    private const string urlRegEx = @"((http|ftp|https)://[w-_]+(.[w-_]+)+([w-.,@?^=%&amp;:/~+#]*[w-@?^=%&amp;/~+#])?)";
    public static MvcHtmlString DisplayWithLinksFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        string content = GetContent<TModel, TProperty>(htmlHelper, expression);
        string result = ReplaceUrlsWithLinks(content);
        return MvcHtmlString.Create(result);
    }
    private static string ReplaceUrlsWithLinks(string input)
    {
        Regex rx = new Regex(urlRegEx);
        string result = rx.Replace(input, delegate(Match match)
        {
            string url = match.ToString();
            return String.Format("<a href="{0}">{0}</a>", url);
        });
        return result;
    }
    private static string GetContent<TModel, TProperty>(HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
    {
        Func<TModel, TProperty> func = expression.Compile();
        return func(htmlHelper.ViewData.Model).ToString();
    }
}

此扩展现在可以在视图中使用:

@Html.DisplayWithLinksFor(model => model.FooBar)

我对解决方案有一些问题:

  1. 它不适用于没有点的主机名,例如本地主机或任何其他 LAN-URL
  2. 它不适用于带有空格的 URL(小问题)
  3. 它没有对我所有其他数据进行编码。因此,如果数据库中有"

最新更新