通过 ajax 将 json 传递给 Page OnGet 方法

Passing json via ajax to Page OnGet method

我有一个数据网格,它使用 PartnersController 的索引操作填充了记录。 更改所选行后,我想显示所选合作伙伴的详细信息(包含详细数据的新页面)。

在我的 Partners\Index.cshtml 中,我有打开新页面的脚本,其中一个参数用于合作伙伴 ID (ppId)。

//...
var obj = { ppId: data.Id };

var myJSON = JSON.stringify(obj);
alert(myJSON); // PRINTS: {"ppId":10531} ---- OK!

var url = '/Partners/Details';

$.ajax({
    url: url,
    type: "GET",
    data: JSON.stringify(obj),
    contentType: "application/json; charset=utf-8",
    success: function (result) {
        alert(result.name);
        window.location = url;  // --- redirection ok!
    },
    error: function () {
        alert("error");
    }
});

这是我的目标 Partners\Details.cshtml Razor 页面:

public class DetailsModel : PageModel
{
    public void OnGet([FromBody]dynamic param)
    {
        Console.WriteLine("Details...PPID:'" + param + "'"); // PRINTS Details...PPID:'' //param is null!
    }
}

所以,我被重定向到详细信息页面,这很好(url 是 localhost/Partners/Details),但是参数为空,并且对如何获取它一无所知。

xhr GET 请求参数如下所示:

[

在这个Details页面中,我的计划是通过OnGet方法获取合作伙伴id,然后将其用于DevExtreme DataGrid DataSource Load参数

.DataSource(d => d.Mvc().Controller("Partners").LoadAction("Details").LoadParams(new { PartnerId = ppId }).Key("Id"));

最后,这整个方法可以吗?

我正在使用 .Net 核心 3.1

您正在 Get 请求中使用 [FromBody],因为模型绑定将尝试绑定正文中的值,而不是查询字符串。此外,作为一种好的做法,您永远不应在 GET 请求中包含 [FromBody] - 从技术上讲,在 GET 请求中发送数据是不可能的。

请试试这个:

public class DetailsModel : PageModel
{
    public void OnGet([FromQuery]string param)
    {
        Console.WriteLine("Details...PPID:'" + param + "'"); // PRINTS Details...PPID:'' //param is null!
    }
}

另外,您的客户端代码不太正确。您应该将参数作为查询字符串传递。见下文

var obj = { ppId: data.Id }; // This is not required

var myJSON = JSON.stringify(obj);
alert(myJSON); // PRINTS: {"ppId":10531} ---- OK!

var url = '/Partners/Details?param=' + data.Id; // Pass the id as a query string

$.ajax({
    url: URL,
    type: "GET",
    success: function (result) {
       alert(result.name);
       window.location = url;  // --- redirection ok!
    },
    error: function () {
        alert("error");
    }
 });