在控制器中接收时,Json数组为null

时间:2016-06-17 16:46:32

标签: arrays json asp.net-mvc

function viewReports(firstDate, lastDate) {
    var selected = $('#ReportSelected').find(":selected");
    var controller = "PortalReports";
    var method = "GetReport";

    var urlAjax = $("#basePath").val() + controller + "/" + method;
    var companydropdown = $('#ReportSelected :selected').data("companydropdown");
    var agencydropdown = $('#ReportSelected :selected').data("agencydropdown");
    var userdropdown = $('#ReportSelected :selected').data("userdropdown");

    var data = 
        {
            reportSelected: selected.text(),
            firstDate: firstDate,
            lastDate: lastDate,
            companydropdown: companydropdown,
            agencydropdown: agencydropdown,
            userdropdown: userdropdown
        };
    /*var data =
        [{
            "reportSelected": selected.text(),
            "firstDate": firstDate,
            "lastDate": lastDate,
            "companydropdown": companydropdown,
            "agencydropdown": agencydropdown,
            "userdropdown": userdropdown
        }];*/

    var answer = JSON.stringify({ data });

    $.ajax({
        traditional: true,
        data: JSON.stringify({ data }),
        url: urlAjax,

        success: function (response) {
            loadReport(response);
        },
        error: function (ob, errStr) {
            alert("An error occured. Please try again.");
        }
    });

//Mvc
     public JsonResult GetReport(JArray data)
            {
           var persons = data.Select(x => x.ToObject<InputJson>());  

JArray数据总是为null,无论我添加删除引号等方括号的方式有多少,我做错了什么! 首选在数组中返回的简单Object以便于阅读,因为我可能需要添加它。

1 个答案:

答案 0 :(得分:1)

由于您要发送复杂的数据结构(数组),因此在进行ajax调用时应指定contentType属性。将contentType属性的值指定为"application/json"

//Values hard coded, you may replace with real values from your form.

var dataArray =    [{
                     reportSelected:'201501',
                     firstDate: '11/12/2010',
                     lastDate: '12/12/2010',
                     companydropdown: 4,
                     agencydropdown: 6,
                     userdropdown: 16,
                   }];

var urlAjax = "/Home/GetReport"; // Hard coded for demo. Read further..
$.ajax({
    type: "POST",
    contentType: "application/json",
    data: JSON.stringify(dataArray),
    url: urlAjax,

    success: function (response) {
        console.log(response);
    },
    error: function (ob, errStr) {
        alert("An error occured. Please try again.");
    }
});

我建议您创建一个视图模型/ DTO来表示您要发送的数据并在您的操作方法中使用它。

public class ReportRequest
{
    public string reportSelected { get; set; }
    public DateTime firstDate { get; set; }
    public int companydropdown { get; set; }
}

[HttpPost]
public JsonResult GetReport(IEnumerable<ReportRequest> data)
{
   //do something with data 
   // to do : Return something
}

在这个例子中,我硬编码了urlAjax变量的值。您可以考虑使用html帮助器方法生成操作方法的正确相对URL路径,如this post中所述。