gpt4 book ai didi

jquery - 如何使用Ajax调用MVC4传递两个字符串数组

转载 作者:行者123 更新时间:2023-12-01 07:38:20 25 4
gpt4 key购买 nike

我想使用 Ajax 将两个字符串数组从 View 传递到 Controller 。但是在传递时显示错误jquery-latest.min.js:4 POST http://localhost:5342/Purchase/ClearCart 500(内部服务器错误)该方法没有传递到 Controller 。尝试使用断点。以下是传递 string[]

的方法
 var items = $('.mids').map(function () {
return $(this).val()
}).get();
var counts = $('.counts').map(function () {
return $(this).val()
}).get();



if (BOLT.response.txnStatus == 'SUCCESS') {

alert("success");
$.ajax({
url: "/Purchase/ClearCart",
type: "POST",
contentType: "application/json",
//dataType: "text",
data: { mid: items, count: counts },
success: function (result) {
alert("success");
},

error: function (e) {
alert("Failed");
}
});

它返回“失败”响应和上述错误。

Controller

[HttpPost]
public void ClearCart(string[] mid,string[] count)
{
int uid=Convert.ToInt32(Session["uid"]);
userService.ClearCart(uid, mid,count);

}

以下是 Mid 和 count 中的值:Values inside Mid and count

最佳答案

您需要在 POST 期间将值绑定(bind)到对象。

  1. 创建要绑定(bind)的类
public class AjaxModel{
public List<int> mid {get;set;}
public List<int> count {get;set;}

// Alternatively, try list string
// public List<string> mid {get;set;}
// public List<string> count {get;set;}
}
  • 修改 ClearCart 以在参数中包含 AjaxModel 模型
  • [HttpPost]
    public ActionResult ClearCart(AjaxModel model)
    {
    return Content(model.mid.Count())

    // int uid=Convert.ToInt32(Session["uid"]);
    // userService.ClearCart(uid, model.mid, model.count);
    }
  • 修改 ajax 调用以包含 contentType: application/json
  • $.ajax({
    url: "/Purchase/ClearCart",
    type: "POST",
    contentType: "application/json",
    data: { mid: items, count: counts },
    success: function (result) {
    alert("success");
    },
    error: function (e) {
    alert("Failed");
    }
    });

    关于jquery - 如何使用Ajax调用MVC4传递两个字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58927114/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com