为什么我的发布数据在此AJAX调用的Controller目标中为空?

时间:2016-04-29 22:00:31

标签: javascript jquery ajax asp.net-mvc

我已经在logan filley的答案here上对我的AJAX调用进行了建模(没有双关语),这看起来很明智且可能有效。这是我在View中的jquery:

$("#btnSaveConfig").click(function () {

    var saveConfigModel = {
        unit: $('#unitsselect').val(),
        scheduleProduceUsage: $('#ckbx_produceusage').checked,
        scheduleDeliveryPerformance: $('#ckbx_deliveryperformance').checked,
        scheduleFillRate: $('#ckbx_fillratebycustomer_location').checked,
        schedulePriceCompliance: $('#ckbx_pricecompliance').checked,
        // TODO: Finish this by storing add'l emails in an array along with the three on the page; 
        recipients: $('#email1').val(),
        generationDayOfMonth: $('#dayofmonthselect').val(),
        generationOrdinal: $('#ordinalselect').val(),
        generationDayOfWeek: $('#dayofweekselect').val(),
        generationWeekOrMonth: $('#weekormonthselect').val(),
        daterangeFromProduceUsage: $('#produsagefrom').val(),
        daterangeToProduceUsage: $('#produsageto').val(),
        daterangeFromDeliveryPerformance: $('#delperffrom').val(),
        daterangeToDeliveryPerformance: $('#delperfto').val(),
        daterangeFromFillRate: $('#fillratefrom').val(),
        daterangeToFillRate: $('#fillrateto').val(),
        daterangeFromPriceCompliance: $('#pricecompliancefrom').val(),
        daterangeToPriceCompliance: $('#pricecomplianceto').val()
    }

    $.ajax({
        type:"POST",
        url:'@Url.Action("PostUnitConfig", "SaveConfig")', 
        async:true,
        contentType: 'application/json',
        dataType:"json",
        data: JSON.stringify(saveConfigModel)
    });
}); // $("#btnSaveConfig").click()

...这是我的模特:

public class SaveConfigModel
{
    public UnitConfigVals unitConfigVals { get; set; }

    public class UnitConfigVals
    {
        public string unit { get; set; }
        public bool scheduleProduceUsage { get; set; }
        public bool scheduleDeliveryPerformance { get; set; }
        public bool scheduleFillRate { get; set; }
        public bool schedulePriceCompliance { get; set; }
        public List<string> recipients { get; set; }
        public int generationDayOfMonth { get; set; }
        public string generationOrdinal { get; set; }
        public string generationDayOfWeek { get; set; }
        public string generationWeekOrMonth { get; set; }
        public int daterangeFromProduceUsage { get; set; }
        public int daterangeToProduceUsage { get; set; }
        public int daterangeFromDeliveryPerformance { get; set; }
        public int daterangeToDeliveryPerformance { get; set; }
        public int daterangeFromFillRate { get; set; }
        public int daterangeToFillRate { get; set; }
        public int daterangeFromPriceCompliance { get; set; }
        public int daterangeToPriceCompliance { get; set; }
    }
}

......和控制器(目前显然是超级斯巴达):

public class SaveConfigController : Controller
{
    public ActionResult PostUnitConfig(SaveConfigModel model) 
    {
        try
        {
            string s = model.unitConfigVals.unit;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        return Json(new { success = true });
    }
}

我到达控制器中的断点(在“ string s = model.unitConfigVals.unit; ”行上),但它会引发异常,因为“model”的值为null。为什么?我的AJAX通话中有什么错误,或者......?!?

更新

我将jquery改为this(更改了布尔赋值并附加了分号):

   $("#btnSaveConfig").click(function() {

      var saveConfigModel = {
        unit: $('#unitsselect').val(),
        scheduleProduceUsage: $('#ckbx_produceusage').attr('checked'),
        scheduleDeliveryPerformance: 
        . . .
    };

    $.ajax({
        type: "POST",
        url: '@Url.Action("PostUnitConfig", "SaveConfig")',
        async: true,
        //contentType: 'application/json',
        dataType: "json",
        data: JSON.stringify({ data: saveConfigModel })
    });
});

...但Controller仍然传递了一个空模型。

更新2

现在我将“ attr('checked')”更改为“('已选中')”,但没有区别......

更新3

“model”在Controller中为null:

public class SaveConfigController : Controller
{
    public ActionResult PostUnitConfig(SaveConfigModel model)

......当AJAX调用是这样的时候:

$.ajax({
    type: "POST",
    url: '@Url.Action("PostUnitConfig", "SaveConfig")',
    async: true,
    dataType: "json",
    data: saveConfigModel
});

...当AJAX调用是这样的时候:

$.ajax({
    type: "POST",
    url: '@Url.Action("PostUnitConfig", "SaveConfig")',
    async: true,
    data: saveConfigModel
});

......而且这个:

$.ajax({
    type: "POST",
    url: '@Url.Action("PostUnitConfig", "SaveConfig")',
    async: true,
    contentType: 'application/json',
    dataType: "json",
    data: JSON.stringify({ model: saveConfigModel })
});

我需要“async:true”吗?我不在我的(工作)GET AJAX调用中使用它。同样,我需要“cache:false”吗?我在那些工作GET AJAX调用中使用它......

更新4

即使我只提供了一些假的信息:

var saveConfigModel = {
    unit: 'Buford', //$('#unitsselect').val(),
    scheduleProduceUsage: true, //$('#ckbx_produceusage').is(':checked'),
    scheduleDeliveryPerformance: false, // $('#ckbx_deliveryperformance').is(':checked'),
    scheduleFillRate: false, //$('#ckbx_fillratebycustomer_location').is('checked'),
    schedulePriceCompliance: false, //$('#ckbx_pricecompliance').is('checked'),
    // TODO: Finish this by storing add'l emails in an array along with the three on the page; might be as easy as declaring an array like this one, and adding to it as necessary
    recipients: 'platypus@whatever.com', // $('#email1').val(),
    generationDayOfMonth: '2nd', //$('#dayofmonthselect').val(),
    generationOrdinal: 'First', //$('#ordinalselect').val(),
    generationDayOfWeek: 'Thursday', // $('#dayofweekselect').val(),
    generationWeekOrMonth: 'month', // $('#weekormonthselect').val(),
    daterangeFromProduceUsage: $('#produsagefrom').val(),
    daterangeToProduceUsage: $('#produsageto').val(),
    daterangeFromDeliveryPerformance: '1', // $('#delperffrom').val(),
    daterangeToDeliveryPerformance: '1', //$('#delperfto').val(),
    daterangeFromFillRate: '1', //$('#fillratefrom').val(),
    daterangeToFillRate: '1', //$('#fillrateto').val(),
    daterangeFromPriceCompliance: '1', //$('#pricecompliancefrom').val(),
    daterangeToPriceCompliance: '1' //$('#pricecomplianceto').val()
};

......它仍然像以前一样永远地在控制器空转。

然后,抓住吸管,我甚至将布尔值包含在单引号中('true'和'false'),但这也(可能是可预测的)也没有区别。

更新5

对于后代,这是有效的AJAX:

$.ajax({
    type: "POST",
    url: '@Url.Action("PostUnitConfig", "SaveConfig")',
    async: true,
    contentType: 'application/json',
    dataType: "json",
    data: JSON.stringify({ model: saveConfigModel })
});

1 个答案:

答案 0 :(得分:1)

由于您回发的值是针对嵌套的base.html类(而不是UnitConfigVals,因此您的控制器方法应为

SaveConfigModel

并且ajax public ActionResult PostUnitConfig(SaveConfigModel.UnitConfigVals model) 选项需要

data

或者你可以保留当前的控制器方法并使用

data: JSON.stringify({ model: saveConfigModel })

虽然你在这里使用嵌套类似乎有点奇怪。

初始代码的其他一些问题

  1. data: JSON.stringify({ model: { unitConfigVals: saveConfigModel }}) 将返回$('#ckbx_produceusage').checked 需要undefined 返回$('#ckbx_produceusage').is(':checked')true
  2. 由于falserecipients,因此需要这样做 List<string>
  3. 但是,构建json数据的所有代码都不是必需的,如果使用强类型recipients: [ 'someValue', 'anotherValue', etc ]方法正确生成视图,那么ajax调用可以像

    一样简单
    HtmlHelper