.NET 8 razor页面中的Ajax post请求方法

问题描述 投票:0回答:1

我遇到问题:我向我的 Ajax 处理程序方法发送多个参数,一个是对象(消费者),其他是 string 和 int,但在该方法中,我总是得到 null。

有人可以帮助我吗?

客户端代码:

var PartyUpdate = parseInt($('#hfIsPartyChange').val(), 10);
     // debugger;
     console.log(consumer);
     $.ajax({
         type: 'POST',
         url: getRootPath() + '/AjaxHandlers/Details?handler=UpdateConsumer',
         headers: {
             'RequestVerificationToken': token
         },
         //  data: '{Consumer:' + JSON.stringify(consumer) + '}',
         data: JSON.stringify({ Consumer: consumer, UpdateConsumer: PartyUpdate, ChannelOfContactibility: "MAIL" }),
        // data: JSON.stringify( consumer ),
        contentType: 'application/json; charset=utf-8',
         dataType: 'json',

Web服务方式:

public class UpdateConsumerRequest
{
      public Consumer Consumer { get; set; }
      public Int32 UpdateConsumer { get; set; }
      public string ChannelOfContactibility { get; set; }
}
 
public IActionResult OnPostUpdateConsumer([FromBody] UpdateConsumerRequest request)
{
    // Access the Consumer object
    Consumer Consumer = request.Consumer; 
 
    Int32 UpdateConsumer =1 ; // Set default value of 1 if not provided
    // Access the ChannelOfContactibility value
    string ChannelOfContactibility =  "MAIL"; 

    // ....
}
ajax asp.net-core .net-core razor-pages
1个回答
0
投票

您可以参考以下代码构建 JS 对象并将数据发送到 Razor 页面的 handler 方法。

    $(function(){
        $("#btnsubmit").click(function(){ 
               var consumer = {};
               consumer.Id=1001;
               consumer.Name = "John"; 

                var PartyUpdate =1002;
                $.ajax({
                    type: "POST",
                    url: "Index?handler=UpdateConsumer",
                    headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() }, //add the verification token to the header. 
                    data: JSON.stringify({ Consumer: consumer, UpdateConsumer: PartyUpdate, ChannelOfContactibility: "MAIL" }),
                    contentType: 'application/json; charset=utf-8',
                });
        });
    });

处理方法:

    public IActionResult OnPostUpdateConsumer([FromBody] UpdateConsumerRequest request)
    {
        // Access the Consumer object
        Consumer Consumer = request.Consumer;

        Int32 UpdateConsumer = 1; // Set default value of 1 if not provided
                                  // Access the ChannelOfContactibility value
        string ChannelOfContactibility = "MAIL";

        // ....
        return new JsonResult(Request);
    }

输出如下:

result

© www.soinside.com 2019 - 2024. All rights reserved.