jqueryasp.net-mvcjquery-ajaxq

Jquery ajax POST call in MVC - include application name hosted in IIS


I am try to use Jquery ajax call - to call one of the controller method, I am using like below. However when in localhost the URL formation is fine. I tried to deploy my application in IIS and created as a separate application, so my URL will be like http://website.com/applicationame/Contollername/methodname.

But while using url: "/Contollername/methodname" --- in my ajx call in js file it is finding the contoller method in :

http://website.com/Contollername/methodname. -- leaving out the application name and throwing error.

Application Name can vary across environments so cannot hardcode. Please let me know if there is a way to handle this.

This ajax call is in separate js file.


 jQuery.ajax({
                type: "POST",
                url: "/Contoller/MethodName",
                data: JSON.stringify(data),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {

}
});

Solution

  • There's multiple options. The situation you are describing is using virtual paths. MVC Razor views can handle virtual paths with the tilda key (~/myrelativeurl). What I would suggest is letting MVC generate the URL and then use that in your Javascript.

    A way would be to use a global Javascript variable to contain the URL that MVC has generated for you, then you can use that URL in your jQuery call.

    <script>
    // whole URL
    var callUrl = '@Url.Action("myAction", "myController")';
    // just the root (this will be the virtual path, if any)
    var siteRoot = '@Request.ApplicationPath';
    </script>
    

    EDIT: as a backup measure you could also fetch the domain + virtual path from the current browser window, but this is obviously not as reliable and maintainable.