ASP.NET MVC Custom Helper – A HttpRequest extension method

31 Aug

Recently I ran into an issue using JQuery’s AJAX library and ASP.NET MVC. Refer to my last post about using JQuery’s AJAX with ASP.NET MVC.

After deploying a solution to my web server I had a major issue where my JQuery $.post method was not working and was not giving me any errors. I immediately thought that there was an error in my server settings or something other then my code because I had no issues in my development environment.

It turned out to be an issue with routing! In my development environment the application was installed under the root directory (‘\’) where as on my server it was installed under a subfolder of the root directory (For example: ‘\test\’) thus the value I coded inside my $.post method was incorrect when deployed to my server.

In order to make it easy for me to deploy to any environment without changing my JQuery method each time I created this simple extension method for the HttpRequest class.

public static class HttpRequestHelper
    public static string AppendServerPath(this HttpRequest request, string path)
        return request.ApplicationPath.EndsWith("/")
                   ? request.ApplicationPath + path
                   : request.ApplicationPath + "/" + path;

So now inside my JQuery method all I have to do is call this method and append the exact path I wish to invoke.\

$.post("<%=Request.AppendServerPath("Test/Controller/DoSomething") %>", null, doSomeThing());

This also worked well inside my Site.Master where I ran into similar issues linking images, style sheets, JavaScript files, etc.

Wherever there is a link in my code I now call this extension method and know it will deploy almost everywhere.



Comments are closed.