如何传递多个输入数组元素值

时间:2019-08-29 13:34:16

标签: javascript c# jquery asp.net-mvc

如您所见,我有一个for循环,其中包含多个ID,并且我想获取IDs的值并将其传递给我的控制器,我该如何实现? >

<form id="UserEdit">
         @for (int i = 0; i < Model.Rights.Count; i++)
          { 
            @Html.HiddenFor(m => m.Rights[i].ID)
          }

       <input id="BtnEditUserJS" onclick="PostFormUserEdit();" type="submit" value="Edit">
 </form>

生成的HTML:

<input id="Rights_0__ID" name="Rights[0].ID" type="hidden" value="31">

<input id="Rights_1__ID" name="Rights[1].ID" type="hidden" value="32">

JavaScript:

function PostFormUserEdit() {  
    $.ajax({
        type: 'POST',
        url: '@Url.Action("EditUser")',
        dataType: 'json',
        data: ,
        success: function (run) {
            console.log('Ok');
            },
        error: function () {
          console.log('something went wrong - debug it!');
            }
        });
}

控制器:

    [HttpPost]
    public JsonResult EditUser(int[] RightId)
    {
        var rights = db.Rights.Where(b => RightId.Contains(b.Id)).ToList();

       //do something with rights
    }

1 个答案:

答案 0 :(得分:1)

您可以这样实现:

function PostFormUserEdit() 
{  
    var arr = [];
    $("#UserEdit input[type='hidden']").each(function (index, obj) {
        arr.push(obj.val());
    });

    $.ajax({
        type: 'POST',
        url: '@Url.Action("EditUser")',
        dataType: 'json',
        data: arr ,   // or you can try data: JSON.stringify(arr)
        success: function (run) {
            console.log('Ok');
            },
        error: function () {
          console.log('something went wrong - debug it!');
            }
        });
}