Url.Action不适用于getJSON

LCJ*_*LCJ 1 asp.net-mvc jquery asp.net-mvc-4

我在MVC4 RAZOR视图项目中有以下jQuery代码.当我对url进行硬编码时,call to action方法正常工作.但是当我使用时Url.Action,它不起作用.

硬编码方法的结果: http://localhost:64994/Search/GetCostpages/?costPageNumber=111

Url.Action方法的结果: http://localhost:64994/@Url.Action(%22Search%22,%20%22GetCostpages%22)?costPageNumber=111

有什么需要纠正才能使它工作?

$(function ()
{
    $("#btnCostPageNumberMagnifingLens").click(function ()
    {

        var costPageNumber = $("#txtCostPageNumber").val();

        //$.getJSON('/Search/GetCostpages/',{costPageNumber: costPageNumber},

        $.getJSON('@Url.Action("Search", "GetCostpages")',{costPageNumber: costPageNumber},
                            function (data) 
                            {

                             alert('Inside Function');

                             });
    });
});
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 5

您不能在单独的JavaScript文件中使用服务器端帮助程序.您可以使用DOM中的url.例如,在这里你有一些不引人注意的AJAXified btnCostPageNumberMagnifingLens元素.

因此,您可以在此按钮上使用HTML5 data-*属性来放置所需的URL:

<input type="button" id="btnCostPageNumberMagnifingLens" data-url="@Url.Action("Search", "GetCostpages")" value="some button" />
Run Code Online (Sandbox Code Playgroud)

然后在你单独的javascript文件中,只需从DOM中读取它并将其用于您的AJAX请求:

$(function () {
    $('#btnCostPageNumberMagnifingLens').click(function () {
        var costPageNumber = $('#txtCostPageNumber').val();
        var url = $(this).data('url');
        $.getJSON(url, { costPageNumber: costPageNumber }, function (data) {
            alert('Inside Function');
        });
    });
});
Run Code Online (Sandbox Code Playgroud)