简体   繁体   English

JSON在MVC 4中不发布包含1个项目的数组

[英]JSON doesn't post array with 1 item in MVC 4

I have my MVC 4 project. 我有我的MVC 4项目。 I have 2 select with multiple options. 我有2个select有多个选项。

<select id="ReportDetailsSelectList" class="form-control ListBox valid" size="10" multiple="">
    <option value="ADMN">Administration</option>
    <option value="ARC">Adminstrative Resource Center</option>
    <option value="BALS">Balance Sheet</option>
</select>

<select id="ReportDetailsSelectList2" class="form-control ListBox valid" size="10" multiple="">
    <option value="ATL">Atlanta</option>
    <option value="BALT">Baltimore</option>
    <option value="BETH">Betheseda</option>
    <option value="CAMD">Camden</option>
</select>

<button id="btnSubmit" name="btnSubmit" type="button" class="btn btn-primary">Submit</button>

I need to collect all selected values from 2 select lists and post it in my Action 我需要从2个select列表中收集所有选择的值,并将其发布到我的Action

Here's my JavaScript Code: 这是我的JavaScript代码:

$('#btnSubmit').click(function () {
    var result = [];
    // Go through Details List
    $('select#ReportDetailsSelectList option:selected').each(function () {
        // Collect Name and Value
        var item = {};
        item.Key = $(this).val();
        item.Value = $(this).text();
        result.push(item);
    });

    var result2 = [];
    // Go through Details List
    $('select#ReportDetailsSelectList2 option:selected').each(function () {
        // Collect Name and Value
        var item = {};
        item.Key = $(this).val();
        item.Value = $(this).text();
        result2.push(item);
    });

    CollectPostData(result, result2);
});

function CollectPostData(result, result2) {
    // Post collected data to the action
    $.ajax({
        url: "/Home/GenerateReport",
        type: "POST",
        data: JSON.stringify({ 'detailList': result, 'detailList2': result2 }),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.status == "Success") {
                alert(data.message);
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occurred!!!");
        }
    });
}

I have a simple class to store my objects: 我有一个简单的类来存储对象:

public class DetailList
{
    public string Key { get; set; }
    public string Value { get; set; }
}

And here's my Controller ActionResult: 这是我的Controller ActionResult:

[HttpPost]
public ActionResult GenerateReport(DetailList[] detailList, DetailList[] detailList2)
{
    return Json(new { status = "Success", message = "Success" }, JsonRequestBehavior.AllowGet);
}

And here's start my problem... A few scenarios: 这就是我的问题了...一些情况:

1) I have multiple option selected in both lists - data posted correctly:

在此处输入图片说明

2) Multiple options in 1st list, 1 option in 2nd list - data posted correctly

在此处输入图片说明

3) 1 option in 1st list, 1 option in 2nd list - First array is null, but the second array posted correctly:

在此处输入图片说明

I have no idea why is that happening? 我不知道为什么会这样? I collect both my arrays absolutely the same way and I post it the same way, but for some reasons, it posted differently. 我以完全相同的方式收集两个数组,并以相同的方式发布它,但是由于某些原因,它发布的方式有所不同。 I checked in Firefox debugger and I see that all data has collected just fine. 我检查了Firefox调试器,发现所有数据都已收集妥当。 Both result and result2 has data, even with 1 item... 即使有1个项目, resultresult2都具有数据...

Anyone, please help, what am I doing wrong here? 有人,请帮助,我在这里做错了什么?

Got it to work. 得到它的工作。

The problem is that MVC doesn't like when you have multiple parameters for a POST, at least not by default in MVC 4. It expects that all of your POST data will be sent as one object. 问题在于,当您有多个POST参数时,MVC不会喜欢,至少在MVC 4中默认情况下不会。它希望所有POST数据都将作为一个对象发送。

Here are the changes I made to your code. 这是我对您的代码所做的更改。

Add the following class: 添加以下类:

public class GenerateReportViewModel
{
    public DetailList[] ListA { get; set; }
    public DetailList[] ListB { get; set; }
}

Change your action method signature: 更改您的操作方法签名:

[HttpPost]
public ActionResult GenerateReport(GenerateReportViewModel viewModel)
{
    return Json(new { status = "Success", message = "Success" }, JsonRequestBehavior.AllowGet);
}

Change your CollectPostData JavaScript function: 更改您的CollectPostData JavaScript函数:

function CollectPostData(result, result2) {
    // Post collected data to the action
    $.ajax({
        url: "/Home/GenerateReport",
        type: "POST",
        data: JSON.stringify({
            ListA: result,
            ListB: result2
        }),
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            if (data.status == "Success") {
                alert(data.message);
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occurred!!!");
        }
    });
}

MVC 5 seems to have made some changes that allow you be more flexible in the patterns you choose, which is why I wasn't able to reproduce it there. MVC 5似乎进行了一些更改,使您可以更灵活地选择自己的模式,这就是为什么我无法在此处进行复制。 Generally, it's easier to manage your POST data if it's all in one object anyway. 通常,如果将POST数据全部放在一个对象中,则管理起来更容易。 Your action method will have fewer parameters (one). 您的操作方法将具有较少的参数(一个)。

Here's another similar SO question that may provide more insight: 这是另一个类似的SO问题,可以提供更多的见解:

Post multiple parameters to MVC Controller using C# 使用C#将多个参数发布到MVC Controller

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM