MVC JQuery/AJAX 如何将数组发送到控制器
MVC JQuery/AJAX How to send array to controller
我正在尝试使用 Jquery/Ajax 从我的视图向控制器发送一个数组。
我有一个 table,其中包含已分配员工的列表和一个不同的 table,用于可用员工。
当用户单击可用员工 table 中的按钮时,它会将其添加到我的 newEmpArray 数组中并将该行着色为绿色。这是有效的。
但我不知道如何将它发送到控制器并解析它以供使用。
如有任何帮助,我们将不胜感激!
查看代码:
<script>
$(document).ready(function () {
console.log("ready!");
var newEmpArray = [];
$(".AddEmp").on("click", function () {
$(this).parents("tr").css("background-color", "green");
var empID = parseInt($(this).parent().siblings().first().text());
newEmpArray.push(empID);
console.log(empID);
});
$("#ShowEmp").on("click", function () {
jQuery.each(newEmpArray, function (index, id) {
console.log("ID: " + newEmpArray[index]);
});
});
$("form#frm").on("submit", (e) => {
e.preventDefault();
let obj = {
id: newEmpArray
};
$.ajax({
url: "@Url.Action("AddEmployee")",
method: "GET",
data: {
data: JSON.stringify(obj)
}
});
});
});
</script>
控制器代码:
public ActionResult AddEmployee(string data)
{
JObject parsedData = JObject.Parse(data);
char[] empIDS = parsedData["id"].ToString().ToArray();
return RedirectToAction("ViewEmployees");
}
我成功了。
查看代码:
$("form#frm").on("submit", (e) => {
e.preventDefault();
$.ajax({
url: "@Url.Action("AddEmployee")",
method: "POST",
traditional: true,
data: { 'ids': newEmpArray }
});
});
控制器代码:
public ActionResult AddEmployee(int[] ids)
{
int[] empArray = (ids);
return RedirectToAction("ViewEmployees");
}
我正在尝试使用 Jquery/Ajax 从我的视图向控制器发送一个数组。 我有一个 table,其中包含已分配员工的列表和一个不同的 table,用于可用员工。
当用户单击可用员工 table 中的按钮时,它会将其添加到我的 newEmpArray 数组中并将该行着色为绿色。这是有效的。
但我不知道如何将它发送到控制器并解析它以供使用。
如有任何帮助,我们将不胜感激!
查看代码:
<script>
$(document).ready(function () {
console.log("ready!");
var newEmpArray = [];
$(".AddEmp").on("click", function () {
$(this).parents("tr").css("background-color", "green");
var empID = parseInt($(this).parent().siblings().first().text());
newEmpArray.push(empID);
console.log(empID);
});
$("#ShowEmp").on("click", function () {
jQuery.each(newEmpArray, function (index, id) {
console.log("ID: " + newEmpArray[index]);
});
});
$("form#frm").on("submit", (e) => {
e.preventDefault();
let obj = {
id: newEmpArray
};
$.ajax({
url: "@Url.Action("AddEmployee")",
method: "GET",
data: {
data: JSON.stringify(obj)
}
});
});
});
</script>
控制器代码:
public ActionResult AddEmployee(string data)
{
JObject parsedData = JObject.Parse(data);
char[] empIDS = parsedData["id"].ToString().ToArray();
return RedirectToAction("ViewEmployees");
}
我成功了。
查看代码:
$("form#frm").on("submit", (e) => {
e.preventDefault();
$.ajax({
url: "@Url.Action("AddEmployee")",
method: "POST",
traditional: true,
data: { 'ids': newEmpArray }
});
});
控制器代码:
public ActionResult AddEmployee(int[] ids)
{
int[] empArray = (ids);
return RedirectToAction("ViewEmployees");
}