c# - How to get links to URLs in text in ASP.NET MVC 4 with Razor syntax? -


i have model text field. text can contain several urls. not have contain urls , not have specific format.

using

@html.displayfor(model => model.textwithsomeurls) 

the text , urls displayed normal text of course. urls displayed working individual links though. there helper method in asp.net / razor?

edit: right output is:

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

which content of text field.

but want urls , urls rendered links this:

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

my solution:

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

this extension can used in views:

@html.displaywithlinksfor(model => model.foobar) 

there no helper that, can create own custom helper or create template displayfor helper, contain logic need.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

debian - 500 Error upon login into Plesk Admin - auth.php3? -