Fer*_*ehy 4 javascript php ajax asp.net-mvc jquery
我有这样一个数组:
var nums=["21", "22", "23", "20", "19", "18"];
Run Code Online (Sandbox Code Playgroud)
和这个JQuery Ajax代码:
$('#chk').click(function () {
$.ajax({
url: "/BarberShop/ServiceUpdate",
type: "Post",
data:{ nums: nums},
dataType: "json",
success: function (data) {
}
});
});
Run Code Online (Sandbox Code Playgroud)
和控制器动作如下:
[HttpPost]
public ActionResult ServiceUpdate(string nums)
{
//Do something......
return View();
}
Run Code Online (Sandbox Code Playgroud)
问题是当我nums在Controller Action中使用ajax 参数发布数组时null,服务器也给我这个错误:
POST http:// localhost:18322/BarberShop/ServiceUpdate 500(内部服务器错误)
n.ajaxTransport.k.cors.a.crossDomain.send @jquery-2.1.4.min.js:4n.extend.ajax @jquery-2.1.4.min.js:4(匿名函数)@ Barbershop:481n. event.dispatch @jquery-2.1.4.min.js:3n.event.add.r.handle @jquery-2.1.4.min.js:3
我在这个链接和其他一些方面尝试了所有答案:
500内部服务器错误 - 上的jQuery的Ajax-后ASP净MVC
但仍然有问题.谢谢
它是null,因为在JavaScript方面,您使用的是数组.
var nums=["21", "22", "23", "20", "19", "18"];
Run Code Online (Sandbox Code Playgroud)
但是,在控制器端,您需要一个字符串.
public ActionResult ServiceUpdate(string nums)
Run Code Online (Sandbox Code Playgroud)
将控制器侧更改为
public ActionResult ServiceUpdate(List<string> nums)
Run Code Online (Sandbox Code Playgroud)
此外,在ajax选项中,请确保设置traditional为true
$.ajax({
url: "/BarberShop/ServiceUpdate",
type: "Post",
data:{ nums: nums},
dataType: "json",
success: function (data) {
},
traditional: true
});
Run Code Online (Sandbox Code Playgroud)
请参阅如何在没有表单的情况下将字符串数组发布到ASP.NET MVC控制器?
更新
你必须使用的原因List<string>与参数绑定有关.当您将数据作为数组ajax时,后端参数绑定器将在要绑定的参数中查找类似的类型/结构.这就是为什么你不能将javascript绑定Array到C#的原因string.
| 归档时间: |
|
| 查看次数: |
5203 次 |
| 最近记录: |