asp.net使用jQuery将多个数据一次发布到多个表中

时间:2018-08-21 00:46:37

标签: jquery asp.net-mvc

想象一下我需要将多个数据发布到多个表中的情况。这是说明情况的一个示例:

假设我希望CustomerNameOrders都在同一页面上,然后一次单击Save保存它们;这是我的HTML:

<div class="form-group">
    <div class="row" style="margin-bottom:5px;">
        <span class="col-md-12">Customer Name</span>
        <input type="text" id="customername"/>
    </div>
    <div id="ulist">
        <ul class="list-group">
            <li class="list-group-item">
                <div class="row">
                    <div class="col-xs-12 col-sm-6 ">
                        <span>Order Name</span>
                        @Html.TextBoxFor(model => model.OrderName)
                    </div>
                    <div class="col-xs-12 col-sm-6">
                        <span>Order Number</span>
                        @Html.TextBoxFor(model => model.OrderNumber)
                    </div>
                </div>
            </li>
            <li class="list-group-item">
                <div class="row">
                    <div class="col-xs-12 col-sm-6 ">
                        <span>Order Name</span>
                        @Html.TextBoxFor(model => model.OrderName)
                    </div>
                    <div class="col-xs-12 col-sm-6">
                        <span>Order Number</span>
                        @Html.TextBoxFor(model => model.OrderNumber)
                    </div>
                </div>
            </li>
        </ul>
    </div>
    <div class="row" style="margin-bottom:5px;">
        <div class="col-xs-12 col-sm-6 col-md-6 col-lg-5 col-xl-4">
            <button type="submit" class="btn btn-block btn-primary" style="max-width:100%; margin-top:10px;" onclick="AddInfo()">Save</button>
        </div>
    </div>
</div>

这是OrderList视图模型:

public class OrderListVM
{
    public string OrderName { get; set; }
    public int OrderNumber { get; set; }
    public string DataJson { get; set; }
}

这是SaveCustomer控制器:

[HttpPost]
public int SaveCustomerOnlyFirst(string CustomerName)
{
    MyCartDBContext db = new MyCartDBContext();
    Customer customer = new Customer();
    customer.CustomerName =CustomerName;
    customer.ExtraInfo = "";
    customer.IsDeleted = false;
    db.Customers.Add(customer);
    db.SaveChanges();
    int latestCustomerId = customer.CustomerId;
    return latestCustomerId;/*ReturnCustomerId on Postback*/
}

[HttpPost]
public ActionResult SaveMultiOrders(int customerId)
{
    MyCartDBContext db = new MyCartDBContext();
    OrderListVM model = new OrderListVM();
    var dataJson = Newtonsoft.Json.JsonConvert.DeserializeObject<List<OrderListVM>>(model.DataJson);

    foreach(var item in dataJson)
    {
        Order order = new Order();
        order.OrderName = item.OrderName;
        orderCustomerId = customerId;
        order.OrderTypeId = item.OrderTypeId;
        db.Orders.Add(order);
        db.SaveChanges();
    }
    return RedirectToAction("Index", "PopulateCustomer");
}

jQuery:

function AddInfo() {
    var cdata = {
        CustomerName: $('#customername').val()
    };
    var OrdersArr = [];
    $("#ulist > ul li").each(function (index, elem) {
        var liElem = {};
        liElem.OrderName = $("ul li .ordername").val();
        liElem.OrderNumber = $("ul li .ordernumber").val();
        OrdersArr.push(liElem);
    });
    var odata = JSON.stringify(OrdersArr);
    $.ajax({
        method: 'post',
        url: '/SaveCustomer/SaveCustomerOnlyFirst',
        data: cdata,
        success: function (customerid) {
            $.ajax({
                method: 'post',
                url: '/SaveCustomer/SaveMultiOrders/?customerid='+customerid,
                data: odata,
                contentType: "application/json",
                success: function () {
                    console.log("CustomerName and Orders Posted Successfully.");
                },
                error: function () {
                    console.log("couldn't Add Orders.");
                }
            });
        },
        error: function(){
            console.log("couldn't Add CustomerName and Orders.");
        }
    });
}

到目前为止,仅过帐客户表,然后发生错误;发送到SaveMultiOrders的内容为空。我找不到正确的方法将订单发布为DataJSON。有人可以请客和帮助吗?

1 个答案:

答案 0 :(得分:0)

您正在url部分中使用查询字符串,而AJAX method已显式设置为POST,因此发生错误,因为找不到具有指定名称的GET控制器操作方法:

url: '/SaveCustomer/SaveMultiOrders/?customerid='+customerid // this is GET query string

应该修改AJAX回调data部分,使其同时包含customerId和JSON数据:

AJAX(SaveMultiOrders

$.ajax({
     method: 'post',
     url: '/SaveCustomer/SaveMultiOrders',
     data: { customerId: customerid, dataJson: odata },
     contentType: "application/json",
     success: function () {
         console.log("CustomerName and Orders Posted Successfully.");
     },
     error: function () {
         console.log("couldn't Add Orders.");
     }
});

控制器操作

[HttpPost]
public ActionResult SaveMultiOrders(int customerId, string dataJson)
{
    // JSON data processing here

    return RedirectToAction("Index", "PopulateCustomer");
}

注意:您可以使用AJAX中的OrdersArr选项将traditional: true直接传递给控制器​​操作,如下所示:

$.ajax({
     method: 'post',
     url: '/SaveCustomer/SaveMultiOrders',
     data: { customerId: customerid, ordersList: OrdersArr },
     traditional: true, // add this line
     success: function () {
         console.log("CustomerName and Orders Posted Successfully.");
     },
     error: function () {
         console.log("couldn't Add Orders.");
     }
});

然后在控制器操作中将参数类型从JSON字符串更改为viewmodel类列表:

[HttpPost]
public ActionResult SaveMultiOrders(int customerId, List<OrderListVM> orderList)
{
    MyCartDBContext db = new MyCartDBContext();
    OrderListVM model = new OrderListVM();
    foreach (var item in orderList)
    {
        // data processing iteration here
    }

    return RedirectToAction("Index", "PopulateCustomer");
}