c# - 通过 JSON 将数组发送到 MVC Controller ?

标签 c# jquery asp.net-mvc json

我正在努力通过 JSON 将数组发送到 MVC Controller 操作。

这是我所拥有的和我尝试过的...

//Get checked records
var $checkedRecords = $(':checked'); //e.g. 3 rows selected = [input 4, input 5, input 6]

//Have tried following:
sendingVar: $checkedRecords.serializeArray(); // gives array of 0's
sendingVar: JSON.stringify($checkedRecords); // gives "{\"length\":1,\"prevObject\":{\"0\":{\"jQuery1313717591466\":1,\"jQuery1313717591653\":13},\"context\":{\"jQuery1313717591466\":1,\"jQuery1313717591653\":13},\"length\":1},\"context\":{\"jQuery1313717591466\":1,\"jQuery1313717591653\":13},\"selector\":\":checked\",\"0\":{}}"...wtf

//Post
$.post(url, { sendingVar: sendingVar }, function(data) {alert(data); });

我该怎么做?

编辑:对于那些建议从顶行“按原样”发送 $checkedRecords 的人 - 这是行不通的。我在 jquery 框架的某个地方遇到了一个奇怪的异常:(

uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://.../.../.../jquery-1.4.4.min.js :: <TOP_LEVEL> :: line 141" data: no]

我认为这意味着它正在尝试将 null 分配给它不能分配给它的东西。

编辑:我使用的是 MVC2 而不是 3

Edit2:在@Monday 的回答之后- 问题是由于我如何构建数组 [input 4, input 5, input 6] 而不是 [4,5,6] - 有什么想法可以代替获取数组中的值吗?

Edit3:如果不是重复,请停止投票。您是否真的阅读了我的问题或阅读了链接的问题?这是一个不同的问题

@达维奥:

I don't want to build in an overriding custom attribute just to send an array from JSON, that is rediculous正如我们已经在这个问题中提到的那样 - 没有必要。

MVC3 - irrelevant

最佳答案

这是我的演示,使用mvc2,希望对您有所帮助~

成功的关键是traditional

traditional参数设置为true

$(function(){
    var a = [1, 2];
    $.ajax({
       type: "POST",
       url: "<%= ResolveUrl("~/Home/PostArray/") %>",
       data: {orderedIds: a},
       dataType: "json",
       traditional: true,
       success: function(msg){alert(msg)}
    });
})

自 jquery 1.4 以来,此参数存在,因为将对象序列化为查询参数的机制已更改。

行动是~

[HttpPost]
public ActionResult PostArray(int[] orderedIds)
{
    return Content(orderedIds.Length.ToString());
}

关于c# - 通过 JSON 将数组发送到 MVC Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7116099/

相关文章:

c# - c# 中 grpc 的 SSL/TSL 支持

c# - 是否可以在 C# 中使用索引来引用类成员变量?

c# - Type.GetType() 带空

javascript - jQuery on() 在 Chrome、Safari 中不起作用。适用于 Firefox

c# - 您可以防止您的 ASP.NET 应用程序关闭吗?

javascript - 突出显示和取消突出显示在 jquery 中选择的元素

jquery - 如何在jQuery或其他平台中创建连接paypal的进度条

asp.net-mvc - ASP.NET MVC Razor, Html.BeginForm, using 语句

javascript - 将值从 MVC Controller 传递到 javascript 代码

c# - 为什么我无法在 Razor 页面上获得正确的文本框值?