简体   繁体   中英

Passing Json Data to MVC Controller

Here I need to pass Json object to the controller.But i have a problem in the MVC JsonResult controller area. I have no idea how to get those objects there. In ItemQtys there are multiple values.

My Code:

    $("#btnSubmit").click(function (e) {

        var itemQtys = [];

        var currentQty;
        $('input.input-qty').each(function (itm) {
            currentQty = $(this).val();
            if (!isNaN(currentQty) && currentQty != '') {
                currentQty = parseInt(currentQty);

                itemQtys.push({
                    ItemId: $(this).attr('data-id'),
                    Qty: currentQty
                });
            }
        });

        var data = {
            UserId: $("#CustomerName option:selected").val(),
            DeliveryInstructions: $('#DeliveryInstructions').val(),
            ItemQtys: itemQtys
        };



        $.ajax({
            type: "POST",
            url: "/Orders/SubmitCustomerOrder",
            contentType: "application/; charset=utf-8",
            dataType: "json",
            data: data,
            async: false,
            success: function (msg) {
                if (msg.length > 0) {
                    $.each(function (response) {
                        //$("#Result").text(response.text);
                    });
                }
            }

        });

    });

MVC Controller: (I want to get the values to here)

 public JsonResult SubmitCustomerOrder(OrdersModels model, int? id)
    {

        return Json(new {  });

    }

My model:

  public class OrdersModels : DbContext
{
    public class CustomerOrders
    {
        public int CustomerOrderId { get; set; }
        //public int CustomerId { get; set; }
        public DateTime OrderDate { get; set; }
        public DateTime DeliveryDate { get; set; }
        public string DeliveryInstructions { get; set; }
        public int Status { get; set; }
        public int Customer_Supplier_CustomerSupplierId { get; set; }
        public DateTime ModifiedDate { get; set; }
        public Guid ModifiedBy { get; set; }
        public bool IsActive { get; set; }
        public List<OrderItems> OrderItemList { get; set; }

    }

    public class OrderItems
    {
        public int OrderItemsId { get; set; }
        public int Products_ProductId { get; set; }
        public int CustomerOrders_CustomerOrderId { get; set; }
        public int Quantity { get; set; }
        public DateTime ModifiedDate { get; set; }
        public Guid ModifiedBy { get; set; }
        public bool IsActive { get; set; }
    }
}

For this scenario you must add a custom model binder for OrdersModels and create your model from httprequest

    public class OrderModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
         var userId=request.Form["UserId"];
          //ToDo
        }

Your Model does not have any properties that can be used to bind - you need something to assign values to which match the schema of the posted data.

If you change your controller method to accept UserId, DeliveryInstructions and ItemQtys as values, your routing should work - you can then use these values to create your object server side.

You can create a JavaScript object which has same fields in CustomerOrders class and pass it as a JSON object to controller on submit as below.

var customerOrders= {};
// fill the object.

$.ajax(
{
    url: 'Controller/SubmitCustomerOrder/',
    data: JSON.stringify({customerOrders: customerOrders, id : id }),
    contentType: 'application/json',
    dataType: 'json',
    type: 'POST',
    success: function (data) {
        // success
    },
    error: function () {
       // error
    }
});

Controller can be as below.

[HttpPost]
public JsonResult SubmitCustomerOrder(CustomerOrders customerOrders, int? id)
{
    return Json(new {  });
}

Please refer following post for more information.

Pass Complex JavaScript Object to MVC Controller

It illustrates how we can pass complex javascript objects to MVC controller.

Thanks !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM