gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:35:25 24 4
gpt4 key购买 nike

如您所见,我有一个带有多个 IDfor 循环,我想获取 ID 的值并将它们传递给我的 Controller ,我怎样才能实现这个目标?

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

Controller :

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

//do something with rights
}

最佳答案

你可以这样实现:

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

关于javascript - 如何传递多个输入数组元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57711380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com