Robin Xing
Robin Xing

Reputation: 123

MVC3 deploy to a directory, url issue

I have a mvc3 web application which will be delopyed to an directory of a website. the address of the application seems like http://wwww.xx.com/aopo/. aopo is the name of the directory. After the deployement I find that the url in js file does not work any more. because I had write the js code with hard code url, just like

$.ajax({url:"/employee/getemployee"})

In that case the request will be sent to http://wwww.xx.com/employee/getemployee instead of http://wwww.xx.com/aopo/employee/getemployee, and 404 is returned. There is lots of code in js like that. I don't want to modify the js. Is there any simple approach to make it work? Can I rewrite the request in global.asax.cs?

Upvotes: 0

Views: 333

Answers (3)

shakib
shakib

Reputation: 5469

One not so clean solution might be,

Setting a url prefix in the layout(in a common place), like

<script type="text/javascript">
    @{
        string root = Url.Content("~/");
        if (root.EndsWith("/", StringComparison.Ordinal))
        {
            root = root.Substring(0, root.Length - 1);
        }
    }
    window.URL_PREFIX = '@root';
</script>

then use the prefix in the ajaxSend hook and change the url.

$(document).ajaxSend(function (event, jqxhr, settings) {
    if (window.URL_PREFIX && settings.url.indexOf(window.URL_PREFIX)) {
        settings.url = window.URL_PREFIX + settings.url;
    }
});

note: If $.ajax() or $.ajaxSetup() is called with the global option set to false, the .ajaxSend() method will not fire.

its not an ideal solution, but might be helpful in a tight situation.

hope this helps.

Upvotes: 2

asawyer
asawyer

Reputation: 17808

I believe you'll need to change your url references to this:

$.ajax({url:"@Url.Action("getemplotee","employee")"})

If this is a script file you can write the correct URL into an element on the page and read that:

<div id='Main' data-url='@Url.Action("getemplotee","employee")' />

Then in your script:

$.ajax({url:$('#Main').data('url')})

Rgarding:

There is lots of code in js like that. I don't want to modify the js

I understand, but you need to use the proper helper methods to account for running under virtual directories, so I would recommending biting the bullet and just fixing it the right way.

Upvotes: 3

Kenneth
Kenneth

Reputation: 28737

No, that's not possible. Since the request doesn't arrive in your application you can't access it and thus you can't rewrite it.

If you have control over the root site, you could use the IIS rewrite module to rewrite the URL to your website.

Upvotes: 1

Related Questions