无法使用Ajax将数据传递到剃须刀页面 [英] Cannot pass data with ajax to razor pages

查看:50
本文介绍了无法使用Ajax将数据传递到剃须刀页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一些数据发送到razor页面方法,但是问题在于方法中它始终将其作为0.

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

此处提供代码:

剃须刀页面:

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);
        }
    });
}

推荐答案

page本质上是使用ASP.NET Core 2.0 Razor Pages时的保留名称.您遇到的问题实际上非常简单,但非常细微:

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:

当看到查询字符串参数时,ASP.NET Core 2.0 Razor Pages框架会将其解释为当前Razor Page的名称.它实际上将包含当前页面的名称.在您的情况下,由于类型是int,因此模型绑定过程无法将字符串(名称)绑定到数字,因此请将其设置为0.

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)

-和-

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

Github ,但这并不特定于您的情况.我建议您搜索或提出一个新问题,专门讨论在Razor页面中使用查询字符串参数.

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.

作为无关的旁注,您无需在$.ajax请求中设置Content-Type标头-在发送内容时使用,而并非在发送内容时使用.

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.

这篇关于无法使用Ajax将数据传递到剃须刀页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆