ASP.Net MVC Routing problem with jQuery AJAX

六眼飞鱼酱① 提交于 2020-01-13 05:14:50

问题


My page is domain.com/home/details/1

In my jQuery AJAX call I have the following however when it makes that call its making a call to domain.com/home/details/home/getdata

What can I do to get it to resolve properly?

$(document).ready(function () {

            oTable = $('#example').dataTable({
                "bServerSide": true,
                "sAjaxSource": "Home/GetData/",
                "bProcessing": true,
                "bPaginate": true,
                "sPaginationType": "full_numbers",
                "bFilter": true,
                "bAutoWidth": false,
                "fnServerData": function (sSource, aoData, fnCallback) {
                    /* Add some extra data to the sender */
                    //aoData.push({ "filtervalue": $('#filtervalue').val(), "Options": $('#Options').val() });
                    $.getJSON(sSource, aoData.concat($('form').serializeArray()), function (json) {
                        /* Do whatever additional processing you want on the callback, then tell DataTables */
                        fnCallback(json)
                    });
                }
            });

        });

回答1:


Absolutely always use URL helpers when dealing with urls in ASP.NET MVC. Absolutely never hardcode urls as you did.

So:

"sAjaxSource": "@Url.Action("GetData", "Home")"

and if this is in a separate javascript file, you could use HTML5 data-* attributes on the #example:

<div id="example" data-url="@Url.Action("GetData", "Home")">
    ...
</div>

and then in your separate js you could use the .data() method:

"sAjaxSource": $('#example').data('url')



回答2:


I think your path should be

"sAjaxSource": "/home/details/home/getdata",

and shouldn't getdata be a filename like getdata.php or something

"sAjaxSource": "/home/details/home/getdata.php",



回答3:


Did you try puting a leading slash before the Ajax Source?

"sAjaxSource": "/Home/GetData/"

UPDATE

As stated in the comments below, hardcoding the URL could cause problems later down the line.

Darin has already posted about using the built in URL helpers so I wont edit my post to include that info. I do it a slightly different way as documented here:

Create Extension methods of UrlHelper to generate your url from Route

I've found this way of working to be extremely helpful when working with a front end team. They found it really easy to understand the Url.RequestedPage() format and it meant they didn't need my help everytime they wanted to link or request something.



来源:https://stackoverflow.com/questions/6453916/asp-net-mvc-routing-problem-with-jquery-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!