开发者

MVC3 call controller method from ajax

I have the followi开发者_开发百科ng code:

$.ajax({
    type: "GET",
    url: "/Search/GetNewData"  //Controller/ActionMethod
   ---snip---
)};

This works fine when run via localhost, however when it is deployed, it cannot find the controller method. I think it's probably a routing problem? But, with only a small limited knowledge using ASP.net, I would appreciate some advice.

Thanks.


You really don't want to specify the URL directly in your JavaScript.

You need to use helpers; otherwise if you change your routes, you'll have to rewrite all the URLS in your JavaScript code. Also, it won't work if your website is hosted in a IIS virtual directory (what seems to be the issue here).

You have a couple solutions here, if your JavaScript code is embedded inside a view, simply use

$.ajax({
    type: 'GET',
    url: '@Url.Action("GetNewData", "Search")'
)};

If it's inside an external JavaScript file, you could, for example, use HTML5 data-* attributes to share the URL to your JavaScript code.

For example:

<div id="foo" data-update-url="@Url.Action("GetNewData", "Search")">
</div>

Then the JavaScript code would be something like

var updateDiv = $('#foo');
$.ajax({
    type: 'GET',
    url: updateDiv.data('update-url'),
    success: function(data) {
       updateDiv.append(data);
    }
)};


The following snippet would work for both virtual directories and web sites.

var baseUri = '@Url.Content("~/")';
$.ajax({
    type: "GET",
    url: baseUri + "Search/GetNewData"  //Controller/ActionMethod
   ---snip---
)};

You can also define the baseUri variable in your layout (above all <script tags) to be able to use it in all included javascripts.


Install FireBug for FireFox. Open .NET panel and Console panels. Request the URL to see whether you get any errors. If none found, then learn to use a debugger. This is by no means a quick fix, but it will help you in the future to fix these sort of problems yourself. Good luck.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜