gpt4 book ai didi

javascript - 使用 Ajax 向 Controller 发送 post 请求时的 Model 与 List

转载 作者:行者123 更新时间:2023-12-01 00:08:34 24 4
gpt4 key购买 nike

我一直在尝试使用ajax将列表模型发送到 Controller ,但它似乎根本不起作用

型号

public string MyModel {
public string myfieldName {get;set;}
}

Controller

 public JsonResult Create(List<myModel> list)
{

return Json("Success");


}

发布请求

 $("body").on("click", "#btnSave", function () {

var list= new Array();
list = [{ myfieldName: 'ABC' }, { myfieldName: 'DEF' }];


//Send the JSON array to Controller using AJAX.
$.ajax({

type: "POST",
url: "/Project/Create",
data: JSON.stringify({ list }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});

因此,当我发送此消息时,我检查浏览器,可以看到请求负载是通过 json 对象列表发送的但是,当我转到 Controller 时,列表根本没有绑定(bind)它,因此我检查 http.context 以检查那里的请求负载,但它全部为空。另一方面,当我像下面这样更改 Controller 时

发送仅包含模型的请求

public JsonResult Create(myModel data)
{

return Json("Success");


}

并更改下面的js

 $("body").on("click", "#btnSave", function () {

var data ={};
data.myfieldName= "test";



//Send the JSON array to Controller using AJAX.
$.ajax({

type: "POST",
url: "/Project/Create",
data: data,
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});

这里唯一的区别是我不以 json 形式发送,所以我的问题是发送模型与使用 ajax 发送模型列表之间的区别是什么我可以改变什么来让 Controller 绑定(bind)数据或接受模型数据列表注意到我正在使用 .Net core 2.0

谢谢

最佳答案

我通常使用此方法将我的 Model 作为 List 发送到我的 Controller 方法。我将尝试向您展示您的场景以及如何执行此操作:

AJAX:

 $("body").on("click", "#btnSave", function () {

var list= new Array();
list = [{ myfieldName: 'ABC'}, { myfieldName: 'DEF'}];


//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "@Url.Action("Create","Project")",
data:{"json": JSON.stringify(list)},
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});

您可以在 Create 方法中像这样接收您的 Model:确保导入 System.Web.Script.Serialization 命名空间:

using System.Web.Script.Serialization

[HttpPost]
public JsonResult Create(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
List<string> myfieldName=new List<string>();
//Access your array now
foreach (var item in jsondata)
{
myfieldName.Add(item["myfieldName"]);
}

//Do something with the list here
return Json("Success");
}

希望这对您有所帮助。

关于javascript - 使用 Ajax 向 Controller 发送 post 请求时的 Model 与 List<Model>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60208483/

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