weixin_33711647 2014-10-28 10:06 采纳率: 0%
浏览 27

MVC AJAX呼叫网址格式

I am working on a small MVC 5 application which has a handful of views and javascript files.

The project structure is pretty standard, i.e. the normal layout for Controllers, Views, Scripts etc but I'm having problems the the AJAX calls within the scripts when I deploy to the client system - where the application is deployed within a Virtual Directory, e.g. http://host/application/.

The issue is caused by the url parameter of the jquery ajax call not resolving consistently. For example, one script is happy with:

$.ajax({ url: 'controller/action' ....});

while another requires

$.ajax({url: '../controller/action' ....});

and most recently another requires

$.ajax({url: '../action' ....});

I can't see that I've done anything differently for these scripts (or controllers or views) so why are the urls being generated differently?

I can work around this for now but want to understand the cause of the problem so i don't get in a mess later.

  • 写回答

3条回答 默认 最新

  • weixin_33735676 2014-10-28 10:17
    关注

    I suggest you generate urls for your javascript server side (these can change if your applications is hosted in IIS as a sub app or something similar). A very helpful tool is T4MVC. Add it via nuget. Check it here.

    You just save the T4 and it will generate strongly typed actions (and a lot of other neat stuff as well).

    Or you can install a visual studio extension that does this for you automatically. It is called autoT4MVC

    What you do then, is create javascript object in razor and have all URLs generated. So if you change your controllers or actions, you will have compile time errors.

    var myUrls = {
       get: '@Url.Action(MVC.MyController.Get())',
       add: '@Url.Action(MVC.MyController.Add())'
    }
    

    Then use it like this:

    $.ajax({url: myUrls.get});
    

    And all your url troubles are solved =)

    评论

报告相同问题?