【问题标题】:Passing array to MVC controller via jQuery通过 jQuery 将数组传递给 MVC 控制器
【发布时间】:2016-04-21 21:59:53
【问题描述】:

尝试从我的 jquery 脚本将对象列表传递给我的 MVC 控制器。控制器没有得到列表。有什么想法吗?

脚本

function refreshXeroData(obj, planId, date, list) {
    // list comes in as a serialized array
    // list = "[{"Id":245225,"XeroFromDate":"4/22/2015 12:00:00 AM","XeroToDate":""},{"Id":245226,"XeroFromDate":"4/1/2016 12:00:00 AM","XeroToDate":"4/30/2016 12:00:00 AM"}]"

    var model = { PlanId: planId, Date: date, List: list };

    $.ajax({
        type: 'POST',
        url: url,
        data: model,
        success: function (data) {
            // code removed for clarity
        },
     });
 }

控制器

public JsonResult Refresh(int planId, DateTime date, List<XeroScenarioModel> list)
{
    // list is null
    // code removed for clarity
}

型号

public class XeroScenarioModel
{
    public int Id { get; set; }
    public string XeroFromDate { get; set; }
    public string XeroToDate { get; set; }
}

【问题讨论】:

  • 首先我会在 ajax 中尝试 data: JSON.stringify(model) ,有时这会有所帮助。接下来我会仔细查看日期。我怀疑您能否将 javascript 日期映射到 C# DateTime 对象。我可能会使用它的日期部分(月、日、年,每个作为单独的值)创建该对象,然后根据这些值在控制器中创建 DateTime 对象。
  • 如果您将列表作为已经序列化的字符串发送,MVC 模型绑定器可能会将其解释为string 而不是List。在将列表字符串添加到模型之前尝试json_decode
  • 添加contentType: "application/json; charset=utf-8",并将其更改为data: JSON.stringify(model)
  • @jmoerdyk 引导我走上正确的道路...在我传入之前,我在列表中使用了 json.Parse()。一切都很好:)。

标签: jquery asp.net-mvc


【解决方案1】:

我浏览了你的代码,试试下面提到的代码。

<script type="text/javascript">
function refreshXeroData() {
    // list comes in as a serialized array
    var planId = 1234;
    var date = new Date();
    list = '[{"Id":245225,"XeroFromDate":"4/22/2015 12:00:00 AM","XeroToDate":"4/30/2016 12:00:00 AM"},{"Id":245226,"XeroFromDate":"4/1/2016 12:00:00 AM","XeroToDate":"4/30/2016 12:00:00 AM"}]';

    var model = { planId: planId, date: "4/30/2016 12:00:00 AM", list: JSON.parse(list) };

    $.ajax({
        type: 'POST',
        url: '../../Sample/Refresh',
        data: JSON.stringify(model),
        contentType: "application/json",
        success: function (data) {
            // code removed for clarity
        },
     });
}

【讨论】:

    【解决方案2】:

    我在传入的数组上使用了 JSON.parse()。

    // list = "[{"Id":245225,"XeroFromDate":"4/22/2015 12:00:00 AM","XeroToDate":""},{"Id":245226,"XeroFromDate":"4/1/2016 12:00:00 AM","XeroToDate":"4/30/2016 12:00:00 AM"}]"
    var model = { PlanId: planId, Date: date, List: JSON.parse(list) };
    
    $.ajax({
       type: 'POST',
       url: url,
       data: model,
       success: function (data) {
           // code removed for clarity
       },
    });
    

    不需要 JSON.stringify()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-21
      • 2018-03-31
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      • 2016-10-28
      • 1970-01-01
      相关资源
      最近更新 更多