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

通过ajax将json传递给Page OnGet方法,json,asp.net-core,razor-pages,asp.net-core-3.1,.net-core-3.1,Json,Asp.net Core,Razor Pages,Asp.net Core 3.1,.net Core 3.1,我有一个datagrid,它使用PartnersController的索引操作填充记录。 更改所选行时,我希望显示所选合作伙伴的详细信息(包含详细信息数据的新页面) 在我的Partners\Index.cshtml中,我有一个打开新页面的脚本,其中有一个partner id(ppId)参数 这是我的目标合作伙伴\Details.cshtml页面: public class DetailsModel : PageModel { public void OnGet([FromBody]dyn

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

在我的Partners\Index.cshtml中,我有一个打开新页面的脚本,其中有一个partner id(ppId)参数

这是我的目标合作伙伴\Details.cshtml页面:

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),但param是null,不知道如何获取它

xhr GET请求参数如下所示:

[

在这个详细信息页面中,我的计划是通过OnGet方法获取合作伙伴id,然后将其用于DevExtreme DataGrid数据源加载参数

.DataSource(d => d.Mvc().Controller("Partners").LoadAction("Details").LoadParams(new { PartnerId = ppId }).Key("Id"));
最后,整个方法行吗


我使用的是.Net core 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");
    }
 });

我设法在JS:window.location('/Partners/Details?ppId='+data.Id)和Details页面中用一行传递参数:OnGet(string ppId)。但是,我仍然想知道我是否可以使用JSON和AJAX方法。有关在Razor页面中使用JSON的一般帮助,请参阅:。有关PageModel中的modelbinding的帮助,请参阅:。DevExtreme还提供了有关您似乎正在尝试的内容的文档:
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");
    }
 });