Pass multiple JSON objects to MVC3 action method

前端 未结 2 1332
天涯浪人
天涯浪人 2020-12-28 18:42

JQuery code:


    //This passes NULL for \"CategoryID\", \"CategoryName\", \"ProductID\", \"ProductName\"
     $(\"#btnPost\").click(function () {
            var         


        
相关标签:
2条回答
  • 2020-12-28 19:02
     var a = $("#a").serialize();
                var b = $("#b").serialize();
                var c = $("#c").serialize();
    
    
         $.ajax(
                {
                    url: '@Url.Content("~/Controller/Method1")',
                    type: 'POST',
                    data: a+b+c,
        success: function (success) {
        // do something
        }
    
        });
    
        // in Controller
        [HttpPost]
        public ActionResult Method1(abc a, bcd b, xyz c)
        {
        }
    
    // where abc, bcd xyz are class
    
    0 讨论(0)
  • 2020-12-28 19:06

    You could send them as JSON request:

    var categoryModel = {
        categoryID: 1,
        categoryName: "Beverage"
    };
    var productModel = {
        productID: 1,
        productName: "Chai"
    };
    $.ajax({
        url: '@Url.Action("ModelTwo")',
        type: 'post',
        dataType: 'json',
        // It is important to set the content type
        // request header to application/json because
        // that's how the client will send the request
        contentType: 'application/json',
        data: JSON.stringify({ cat: categoryModel, prd: productModel }),
        cache: false,
        success: function (result) {
            alert(result);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(thrownError);
        }
    });
    

    The JSON.stringify method that I am using in my example is natively built-in all modern browsers but if you need to support legacy browsers you could include the json2.js script to your page.

    This should correctly bind to the following action:

    [HttpPost]
    public ActionResult ModelTwo(Category cat, Product prd)
    {
        return Json(new { message = "this took multiple model..." });
    }
    

    But I would recommend you defining a view model:

    public class MyViewModel
    {
        public Category Cat { get; set; }
        public Product Prd { get; set; }
    }
    

    and then have your controller action take this view model:

    [HttpPost]
    public ActionResult ModelTwo(MyViewModel model)
    {
        return Json(new { message = "this took a single view model containing multiple models ..." });
    }
    

    and of course the client side code stays the same.

    0 讨论(0)
提交回复
热议问题