Url Helper Extension Method for ASP MVC in form tags when using IIS 6
Posted in aspmvc, Uncategorized on December 21st, 2009 by taswar
So I was going through some code of codebettercanvas and found it interesting of Karl Seguin using Html Helper extension for his form tags, which has its elegance.
e.g
1 | <form id="login" action="!{Html.LinkTo<HomeController>(c => c.Login()) }" method="post"> |
Basically it calls an extension method called LinkTo with a generic controller and a lamda for calling its action, the extension method looks like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public static class HtmlExtensions { private static readonly string _applicationPath = HttpContext.Current.Request.ApplicationPath == "/" ? string.Empty : HttpContext.Current.Request.ApplicationPath; //other method removed public static string LinkTo(this HtmlHelper html, Expression<Func<T, ActionResult>> action) { var body = action.Body as MethodCallExpression; if (body == null) { throw new InvalidOperationException("Expression must be a method call"); } var controller = typeof(T).Name.Replace("Controller", string.Empty); return string.Format("{0}/{1}/{2}", _applicationPath, controller, body.Method.Name); } } |
This would work great if you are using IIS 7 or some kind or rewrite in your URL but if you are using IIS 6, where you might need some special extension in your routes for IIS 6 to surf ASP MVC e.g {controller}.mvc/{action}/{id} pattern. (Steve Sanderson does a post on deploying it on IIS 6) Then you are out of luck to use the html helper extension method form tag. Since the application path does not know about the .mvc extension you added to the route.
But not to worry one can use the UrlHelper class to find the path. Here is an example of it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public static class UrlHelperExtension { public static string LinkTo(this UrlHelper helper, Expression<Func<T, ActionResult>> action) { var body = action.Body as MethodCallExpression; if (body == null) { throw new InvalidOperationException("Expression must be a method call"); } var controller = typeof(T).Name.Replace("Controller", string.Empty); return helper.Action(body.Method.Name, controller); } } |
Now all you have to do is use this in your form e.g
1 | <form id="login" action="!{Url.LinkTo<HomeController>(c => c.Login()) }" method="post"> |
Please note I am using sparkviewengine for my views in my asp mvc
4 Responses
Leave a Comment

October 20th, 2010 at 4:10 pm
Thanks for a wonderful blog, will add my Digg account!
November 2nd, 2010 at 10:57 am
Another great blog post. I shared this on my Facebook – you should think about adding a “like” button to your blog.
November 6th, 2010 at 6:22 pm
Thanks for a great post, will add my bookmarking account!
November 7th, 2010 at 1:20 pm
Finally found a website that I can enjoy. Have you thought about adding a Facebook fan page?