【问题标题】:Trouble sending an array to a model in MVC无法将数组发送到 MVC 中的模型
【发布时间】:2015-06-18 07:47:03
【问题描述】:

我有什么:

这样的模型:

public class ProductModel
{
    public string ProductName { get; set; }
    public List<string> SkipUpdates { get; set; }
}

这样的控制器方法:

public ActionResult GetProductUpdates(ProductModel productModel)
{
   return View("AddEdit");
}

暂时不做任何事情,只是想确保来自 JS 的数据正确输入。

JS:

function productModel() {
    this.productName = "";
    this.SkipUpdates = [];
}

填充模型和 AJAX:

var newProductModel = new productModel();

var options = $('#AdditionalSkipDates  option');
        var skipDates = [];

        options.each(function (i, option) {
            skipDates[i] = $(option).text();
        });

newProductModel.productName = "ABC";
newProductModel.SkipUpdates = skipDates;

$.ajax({
        type: "GET",
        url: urlToGetProductSchedule,
        data: newProductModel,
        dataType: "json"
    }).success(function () {

    }).fail(function (xhr) {
        alert("Something went wrong!!!");
        console.log(xhr.responseText);
    });

AdditonalSkip dates 是一个包含一堆日期的列表框。

发生了什么:

SkipUpdates 数组确实具有我可以在浏览器控制台中看到的值。 在控制器中放置一个断点,它会命中该方法。 SkipUpdates 值为 null。

没有发生什么:

如何让数组进入控制器?

提前致谢。

【问题讨论】:

  • 您没有向集合值添加索引器。您可以查看对数据进行字符串化(JSON.stringify()) and/or using the traditional: true,` 选项。但是您为什么要发回所有选项(而不仅仅是选定的值?)
  • Stephen 发布所有选项或仅发布所选选项都没有关系。就是要发布的数组。
  • 是的,数组将包含所有选项,如果 id id 有效,您将无法知道选择了哪些选项。

标签: javascript c# arrays asp.net-mvc


【解决方案1】:

在发送之前尝试对对象进行字符串化:

$.ajax({
        type: "GET",
        url: urlToGetProductSchedule,
        data: JSON.stringify(newProductModel),
        dataType: "json"
    }).success(function () {

    }).fail(function (xhr) {
        alert("Something went wrong!!!");
        console.log(xhr.responseText);
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2020-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多