通过AJAX将Javascript数组发布到控制器

时间:2015-12-22 13:49:46

标签: javascript ajax model-view-controller controller

我可以接受工作但是ı无法在控制器端获得jobItem。我检查了JobItem列表不是空的但是我没有上控制器

 var Job = { "Name": "", "Date": "", "Description": "", "AuthPersonId": "", "ClientId": "", "DealerId": "", "JobItem": [] };
    var JobItem = { "": "", "ItemId": "", "Quantity": "" };


    Job.Name = $("#Name").val();
    Job.Date = $("#Date").val();`enter code here`
    Job.Description = $("#Description").val();
    Job.AuthPersonId = $("#AuthPersonId").val();
    Job.ClientId = $("#clientName").attr("data-id");
    Job.DealerId = $("#dealerName").attr("data-id");

    alert(Job.ClientId + "scas" + Job.DealerId);
    for (var w = 0; w < Urunler.length; w++) {
        JobItem.ItemId = $(".I-" + w).attr("data-ItemId");
        JobItem.Quantity = $(".I-" + w).attr("data-urunAdet");
        alert(JobItem.ItemId + "--" + JobItem.Quantity)
       console.log(JobItem)
    }


    $.ajax({
        url: '/Jobs/Save',
        data: JSON.stringify(Job),
        type: 'POST',
        contentType: 'application/json;',
        dataType: 'json',
        traditional : true,
        success: function (result) {

            if (result.Success == "1") {
                window.location.href = "/Company/index";
            }
            else {
                alert(result.ex);
            }
        }
    });
public JsonResult Save(Job Job)
    {
        try
        {

            if (ModelState.IsValid)
            {
                db.Job.Add(Job);
                db.SaveChanges();
                JobItem jbitm=new JobItem();
                //jbitm.ItemId=Job.JobItem.First().ItemId;
                //db.JobItem.Add(Job.JobItem.ToList())
                return Json(new { Success = 1});
            }
        }
        catch (Exception ex)
        {
            return Json(new { Success = 0, ex = ex.Message.ToString() });
        }

        return Json(new { Success = 0, ex = new Exception("Unable to save").Message.ToString() });
    }

我可以接受工作但是ı无法在控制器端得到jobıtem。我检查了JobItem列表不是空的但是我没有上控制器

3 个答案:

答案 0 :(得分:0)

为什么使用空字符串作为属性名称?

  

var JobItem = {“”:“”,“ItemId”:“”,“数量”:“”};

尝试删除“”:“”

并且,请发布JobItem类定义。

答案 1 :(得分:0)

您将Job.JobItem初始化为null,然后初始化JobItem,但后来我看不到:

  

Job.JobItem = JobItem

答案 2 :(得分:0)

我想这应该推送到JobItems?

所以也许改变一下:

alert(Job.ClientId + "scas" + Job.DealerId);
for (var w = 0; w < Urunler.length; w++) {
    JobItem.ItemId = $(".I-" + w).attr("data-ItemId");
    JobItem.Quantity = $(".I-" + w).attr("data-urunAdet");
    alert(JobItem.ItemId + "--" + JobItem.Quantity)
   console.log(JobItem)
}

为:

for (var w = 0; w < Urunler.length; w++) {
    var newJobItem = {
        ItemId: $(".I-" + w).attr("data-ItemId"),
        Quantity: $(".I-" + w).attr("data-urunAdet");
    };
    Job.JobItem.push(newJobItem);
}