Cannot pass data with ajax to razor pages

梦想的初衷 提交于 2019-12-31 03:43:26

问题


I am trying to send some data to razor page method, but the problem is that in method it takes always as 0.

Heres the code:

Razor Page:

public IActionResult OnGetProducts(int page)
{
    var products = _productRepository.GetProducts();

    decimal pagesInDecimal = (products.Count() / 18);
    var totalPages = pagesInDecimal % 1 == 0 ? pagesInDecimal : pagesInDecimal + 1;

    products = products.Skip((page - 1) * 20).Take(20);

    return new JsonResult(new {
        totalPages = totalPages,
        products = products
    });
}

Ajax:

getProducts(1);            
function getProducts(page) {
    $.ajax({
        type: 'GET',
        url: "/Products",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: {
            page: page,
            handler: 'Products'
        },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        success: function (datas) {
            console.log(datas);
        }
    });
}

回答1:


page is essentially a reserved name when using ASP.NET Core 2.0 Razor Pages. The problem you have is actually quite simple, yet very subtle:

When it sees a query-string parameter, the ASP.NET Core 2.0 Razor Pages framework interprets this as the name of the current Razor Page - You can see that if you change your page parameter to type string; it'll actually contain the name of the current page. In your case, because the type is an int, the model-binding process cannot bind a string (the name) to a number, so sets it to 0.

One way to work around this issue is to use a different name. e.g.:

public IActionResult OnGetProducts(int pageNumber)

-and-

data: {
    pageNumber: page,
    handler: 'Products'
}

There's a fair bit of discussion around this issue on Github, but it's not specific to your scenario. I suggest you either search for or raise a new issue that specifically talks about using a query-string parameter in a Razor Page.

As an unrelated side note, you don't need to set the Content-Type header in your $.ajax request - This is used when you are sending content, which you're not.



来源:https://stackoverflow.com/questions/47848183/cannot-pass-data-with-ajax-to-razor-pages

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