【问题标题】:How to use multiple arrays as parameters for a httppost method ins asp.net mvc如何在asp.net mvc中使用多个数组作为httppost方法的参数
【发布时间】:2018-03-16 13:12:40
【问题描述】:

如何使用我拥有的两个数组作为控制器中方法的参数?我以为使用 AJAX 就可以了,但我不知道如何传递这两个数组。

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);
}

【问题讨论】:

  • 你的控制器方法的签名是什么,模型是什么?你是如何填充这些数组的?
  • 如果你生成了正确的表单控件,那么它只是data: $('form'.serialize()) - 并删除contentType 选项(无论如何'html' 是没有意义的)
  • 我编辑了帖子的内容。

标签: asp.net arrays ajax asp.net-mvc asp.net-ajax


【解决方案1】:
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("");
    }

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2013-10-09
    • 1970-01-01
    • 2020-09-27
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多