将对象参数从CSHTML视图传递到ASP.net Core中的控制器

时间:2019-05-21 06:45:09

标签: c# asp.net razor view controller

我正在尝试将某些对象值从MVC视图传递到控制器。但是遇到值无法传递到我的控制器的问题,因为它一直抱怨值未传递?我在这里需要注意对象类型的格式或某些编码设置吗?

控制器代码

public class saveViewModel
{
  public List<NgpartDetails> ngpartDetails { get; set; }
  public List<GeneralDetails> generalDetails { get; set; }  
}

[HttpPost]
public void MyActionSubmit(saveViewModel viewModel)
{ 

    foreach (var ngpartdetail in viewModel.ngpartDetails)
    {
        NgpartDetails Ng1 = new NgpartDetails { Number = ngpartdetail.Number,
        Quantity = ngpartdetail.Quantity, Reason = ngpartdetail.Reason, Nghandling = ngpartdetail.Nghandling,
        Remarks = ngpartdetail.Remarks };

        efngpartdetails.NgpartDetail.Add(Ng1);
    }

    efngpartdetails.SaveChanges();

}

javascript代码

$("body").on("click", "#buttonSubmit", function () {
    console.log("button submit clicked")

    var generalDetails = [];
    generalDetails.push({
        Date: $("#date").val(),
        LotNo: $("#lotno").val(),
        PartName: $("#partname").val(),
        LotProductionDate: $("#lotproductiondate").val(),
        Number: $("#partno").val(),
        ImportQty:$("#importquantity").val()
    })

    var ngpartDetails = [];

    $("#ngpartdetails TR.data-row").each(function () {
        var row = $(this);
        ngpartDetails.push({
            Number : row.find("TD").eq(0).html(),
            Quantity : row.find("TD").eq(1).html(),
            Reason : row.find("TD").eq(2).html(),
            Nghandling : row.find("TD").eq(3).html(),
            Remarks : row.find("TD").eq(4).html()
        });

    });

    var viewModel = {
        ngpartDetails: ngpartDetails,
        generalDetails: generalDetails
    }


    $.ajax({
        type: "POST",
        url: "/Home/MyActionSubmit",
        data: "{'viewModel':" + JSON.stringify(viewModel) + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function () {
            alert("Successfully sent ngpartdetails to controller.");
        },
        error: function () {
            alert("Passing data to controller failed");
        }
    });
});

我希望viewModel数据将成功传递到控制器,但是在调试时它说viewModel在控制器上包含空对象。

0 个答案:

没有答案