【问题标题】:Send 2 array of objects from jquery to MVC controller将 2 个对象数组从 jquery 发送到 MVC 控制器
【发布时间】:2017-10-31 11:36:41
【问题描述】:

我在Controller上有以下方法:

public ActionResult TestMultipleParameters(IEnumerable<TestM> competences, IEnumerable<long> extracompetences)
        {
            return Json("success", JsonRequestBehavior.AllowGet);
        }

对象是:

public class TestM
{
   public string uid { get; set; }
   public long Id { get; set; }
   public bool IsFromParent { get; set; }
}

从查询中我想发送这个:

var competences = [ {uid: "a", Id: 1, IsFromParent: true}, {uid: "b", Id: 2, IsFromParent: false}];
var extraCompetences = [1, 2, 3];
jQuery.ajaxSettings.traditional = true;
$.ajax({
   url: ...,
   async: true,
    data: JSON.stringify({ competences: competences, extracompetences: extracompetences }),
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    type: 'GET',
    error: handleException,
    success: function(data){
        console.log("success");
    }
})

我尝试了 JSON.stringify 和 not stringify 之间的许多组合,但数据没有发送到 MVC。如果没有 JSON.stringify,则将数组发送到控制器,但 TestM 的值是默认值。

【问题讨论】:

    标签: jquery json asp.net-mvc


    【解决方案1】:

    你做了一个 GET。 GET 没有正文,您的 contentType 选项将被忽略。

    您可以对使用[HttpPost] 修饰的方法进行 POST,或者您需要使用索引器生成名称/值对,但是数据将作为查询字符串发送,您可能会超过查询字符串限制并抛出异常。

    如果进行 GET,则 data 需要采用以下格式

    data: { competences[0].uid: "a", competences[0].Id: 1, ..... competences[1].uid: "b", .... },
    

    【讨论】:

    • 我将 ajax 调用更改为 POST,但现在出现此错误:“System.ArgumentException: Invalid JSON primitive: rights.”
    • 如果您已将其更改为type: 'POST',,您仍然需要data: JSON.stringify({ competences: competences, extracompetences: extracompetences }),contentType: 'application/json; charset=utf-8',(并用[HttpPost] 标记方法。作为旁注,您不需要traditional = true - 仅适用于简单值数组
    猜你喜欢
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多