Wie erhalte ich Links zu URLs in Text in ASP.NET MVC 4 mit Razor-Syntax?
Ich habe ein Modell mit einem Textfeld. Der Textkönnen mehrere URLs enthalten. Es muss keine URLs enthalten und hat kein bestimmtes Format.
Verwenden
@Html.DisplayFor(model => model.TextWithSomeUrls)
Der Text und die URLs werden natürlich wie normaler Text angezeigt. Ich möchte, dass die URLs als funktionierende Links angezeigt werden. Gibt es in ASP.NET / Razor eine Hilfsmethode dafür?
Bearbeiten: Im Moment ist die Ausgabe:
http://www.google.com, foo: bar; http://www.yahoo.com
Welches ist genau der Inhalt des Textfeldes.
Aber ich möchte die URLs und nur die URLs erhalten, die als Links wie folgt gerendert werden:
<a href="http://www.google.com">http://www.google.com</a>, foo: bar; <a href="http://www.yahoo.com">http://www.yahoo.com</a>
Meine Lösung:
public static partial class HtmlExtensions
{
private const string urlRegEx = @"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)";
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();
}
}
Diese Erweiterung kann jetzt in Ansichten verwendet werden:
@Html.DisplayWithLinksFor(model => model.FooBar)