2017-10-05 59 views
-2

如何使用兩個數組作爲控制器中的方法的參數?我認爲使用AJAX會做,但我不知道如何通過這兩個數組。如何使用多個數組作爲httppost方法的參數在asp.net mvc

var arrayIngredientId = new Array(); 
var arrayQuantity = new Array(); 

//Some code here to get the values of the arrays. 
//I did a loop that inserts the data to the arrays through a variable ctr that increments 

$.ajax({ 
    type: "post", 
    url: "/Recipes/Create", 
    contentType: "html", 
    dataType: 'json', 
    data :{ 
     //I don't know what should I put here 
    }, 
    traditional: true, 
    success: function (result) { 
     alert.log(data.result) 
    }, 
    error: function(data){ 
     alert("fail"); 
    } 
}) 

//The method I have for controller. I don't know what parameters should I put 
[HttpPost] 
public JsonResult Create() 
{ 
    return Json(new { result = "success" }, JsonRequestBehavior.AllowGet); 
} 
+0

什麼是你的控制器方法的簽名,是什麼型號?你如何填充這些數組? –

+0

如果你已經正確地生成了你的表單控件,那麼它的簡單的'data:$('form'.serialize())' - 並移除'contentType'選項(它無論如何都不會成爲html) –

+0

編輯帖子的內容。 – AyakoS

回答

0
var arrayIngredientId = new Array(); 
var arrayQuantity = new Array(); 

$.ajax({ 
        type: "POST", 
        data: { objName: JSON.stringify({ arrayQuantity : arrayQuantity ,arrayIngredientId : arrayIngredientId }) }, 
        url: '@Url.Action("Create", "Recipes")', 
        dataType: "json", 
        success: function (msg) { 
         alert(msg); 
        }, 
        error: function (e) { 
        } 
       }); 

//Controller side 
[HttpPost] 
    public ActionResult Create(string objName) 
    { 
     dynamic d = JObject.Parse(objName); 
     int totalarrayIngredientId= d.arrayIngredientId.Count; 
     var vertex = ""; 
     for (int i = 0; i < totalarrayIngredientId; i++) 
     { 
      //get like d.arrayIngredientId[i].YourKeyName 
     } 

     return Json(""); 
    } 
相關問題