【问题标题】:MVC JQuery/AJAX How to send array to controllerMVC JQuery/AJAX 如何将数组发送到控制器
【发布时间】:2020-12-11 09:47:10
【问题描述】:

我正在尝试使用 Jquery/Ajax 将数组从我的视图发送到控制器。 我有一个包含已分配员工列表的表和一个用于可用员工的不同表。

当用户单击可用员工表中的按钮时,它会将其添加到我的 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");
        }

【问题讨论】:

    标签: jquery ajax model-view-controller


    【解决方案1】:

    我搞定了。

    查看代码:

    $("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");
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      • 2016-01-20
      • 2020-12-30
      相关资源
      最近更新 更多