Jak uzyskać linki do adresów URL w tekście w ASP.NET MVC 4 ze składnią Razor?
Mam model z polem tekstowym. Tekstmogą zawierają kilka adresów URL. Nie musi zawierać adresów URL i nie ma określonego formatu.
Za pomocą
@Html.DisplayFor(model => model.TextWithSomeUrls)
tekst i adresy URL są oczywiście wyświetlane jak normalny tekst. Chciałbym jednak, aby adresy URL były wyświetlane jako działające pojedyncze linki. Czy istnieje metoda pomocnicza dla tego w ASP.NET / Razor?
Edytować: W tej chwili wyjście jest:
http://www.google.com, foo: bar; http://www.yahoo.com
Jaka jest dokładnie treść pola tekstowego.
Ale chcę uzyskać adresy URL i tylko adresy URL renderowane jako linki w ten sposób:
<a href="http://www.google.com">http://www.google.com</a>, foo: bar; <a href="http://www.yahoo.com">http://www.yahoo.com</a>
Moje rozwiązanie:
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();
}
}
To rozszerzenie może być teraz używane w widokach:
@Html.DisplayWithLinksFor(model => model.FooBar)