【问题标题】:Posting array from Ajax to cshtml.cs using .NET Core使用 .NET Core 将数组从 Ajax 发布到 cshtml.cs
【发布时间】:2021-09-15 14:41:26
【问题描述】:

我正在使用 .NET Core,并尝试通过 Ajax 从 .cshtml 页面将数组发送到相应的方法。我有一个强类型类,我希望数组绑定到该类,但是当调用该方法时,它返回 null。我已经设法发回简单的数据(例如单个字符串),但是任何类似数组的数据都返回 null。

这是 Ajax 调用和我尝试发送的数组。

var miniPediPrice = document.getElementById("MiniPedi").value * 1500;
    var miniPediDuration = parseFloat('@Model.miniPedi.Duration');
    const products = [{
        Name: '@Model.miniPedi.Name',
        Price: miniPediPrice.toString(),
        Duration: miniPediDuration.toString(),
        GelPolish: "false",
        NailArt: "false"
    }]


    console.log(products);
    const total = 0;
    try {
        $.ajax({
            dataType: 'json',
            type: 'POST',
            url: "/Products?handler=CalculatePrice",
            traditional: true,
            data: JSON.stringify(products),
            //data: JSON.stringify({ products: products }),
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            success: function (data) {
                console.log(data);
                $("#totalPrice").val(data)


            },
        });
    } catch (e) {

    }

ajax 调用的方法。 “产品”始终为空。

public IActionResult OnPostCalculatePrice([FromBody] List<Products> products)
{          
        var totalPrice = "";// product.Name;

        //TotalPrice = "£" + (totalPrice / 100).ToString();
        return new JsonResult(totalPrice);
}

产品的模型类:

public class Products
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public decimal Duration { get; set; }
    public bool GelPolish { get; set; }
    public bool NailArt { get; set; }

    public Products(string productName, decimal productPrice, decimal productDuration, bool gelPolish, bool nailArt)
    {
        Name = productName;
        Price = productPrice;
        Duration = productDuration;
        GelPolish = gelPolish;
        NailArt = nailArt;
    }
}

我已经到处搜索了如何解决这个问题,但没有运气。我是 jQuery/Javascript 新手,所以我还在学习语法等。我希望发布的信息足够。

【问题讨论】:

    标签: c# jquery ajax asp.net-core .net-core


    【解决方案1】:

    您可以执行以下步骤以使其正常工作。

    1:从produst 中删除构造函数。

    2:更改你的ajax like(添加contentType: "application/json"decimal,bool类型无需转换为字符串):

     var products =
            [{
                Name: "assad",
                Price: 12.5,
                Duration:4.5,
                GelPolish: false,
                NailArt: false
            }];
    
          $.ajax({
            dataType: 'json',
            contentType: "application/json",
            type: 'POST',
            url: "/Products?handler=CalculatePrice",
            traditional: true,
            data: JSON.stringify(products),
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            success: function (data) {
                console.log(data);
                $("#totalPrice").val(data)
    
            },
        });
    

    3:你的行动:

    public IActionResult OnPostCalculatePrice([FromBody] List<Products> products)
    {          
            var totalPrice = "";// product.Name;
    
            //TotalPrice = "£" + (totalPrice / 100).ToString();
            return new JsonResult(totalPrice);
    }
    

    测试结果:

    【讨论】:

    • 从 products 类中删除构造函数使其工作!感谢您的回复:)
    【解决方案2】:

    可以吗

    1. 添加'contentType':'application/json';在您的 ajax 调用中。
    2. 不要做JSON.stringfy。直接使用data中的产品。
    3. 从 Products.cs 类中删除构造函数(它应该是 Product 因为您正在传递数组列表来表示产品)
    4. 指定价格、持续时间十进制值和 GelPoslish、NailArt 布尔值(不带引号的布尔值。)

    .

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-20
      • 2013-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      • 1970-01-01
      • 2021-09-07
      • 2013-07-27
      相关资源
      最近更新 更多