如何将对象列表从视图中的Java脚本代码传递到控制器中的操作方法

问题描述 投票:2回答:1

我在JavaScript编程方面经验不足。我想将对象列表从“视图”中的javascript代码传递到MVC“控制器”中的操作方法。这是我想要实现的目标–

MVC模型和控制器:

 Public Class Student
    {
        Public int Id {get; set;}
        Public string Name {get; set;}
        Public string Address {get; set;}
    }

    Public class StudentController : Controller
     {
        Public ActionResult Index()
        {
            // Read the data from database, create a list of “Student”
            return View(“Display”, StudentList);
        }

        [HttpPost]
        Public ActionResult OrderStudentList(List<Student> StudentList)
        {
            // Code to ascend/descend list
        }
     }

Display.cshtml

    @model IEnumerable<Student>
    // Code that displays student list
    <button onclick="myFunction()">Student Name</button>
    <script>
        function myFunction()
            {
                var studentL = @Model.ToList();
                $.ajax({
                url: "@Url.Action("OrderStudentList ", "Student")",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({ StudentList: studentL }),
                success: function (response) {
                response ? alert("It worked!") : alert("It didn't work.");
                }
            });    
    </script>

如您所见,我正在将“学生”列表传递给名为“显示”的视图。该视图有一个名为“学生姓名”的按钮。单击该按钮时,我想将“学生”列表传递给操作方法“学生控制器”中的“ OrderStudentList”,该方法将列表按升序/降序排列。但是,当我运行代码时,在“ OrderStudentList”方法中,列表从未获得任何值。

这是到目前为止我在上面的代码中为分配数据值所做的尝试

    data:’@Html.Raw(Model.ToList())’
    data: @Html.Raw(Json.Encode(Model.ToList()));
 Converted a list to an array and tried to copy each element of a list 
   individually to an element of javascript array as follows
        var arrayJs = [];
        for(var i=0; i<= @Model.Count(); i++)
        {
            arrayJs.push(@Model.ElementAt(i));
        }
   But it gives the syntax error with the “i does not exist in 
   the current context”.
 Created a ViewModel with Student list as a property
        Class StudentList
        {
            Public List<Student> StudentList {get; set;}
        }
   Tried passing an instance of a viewModel as a JSON object to action  
   method “OrderStudentList”.

没有任何作用。如果有人帮助,我将不胜感激。谢谢

javascript c# model-view-controller
1个回答
0
投票
<button onclick="myFunction()">Student Name</button>

//这是必须使用$语法包含的jquery。它可用//在项目目录中,您只需检查并更新以下行。

 <script type="text/javascript">   
    function myFunction() {
        var studentL =  @Html.Raw(Json.Encode(Model));

        $.ajax({
            url: "@Url.Action("OrderStudentList", "Student")",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({ StudentList: studentL }),
            success: function (response) {
                response ? alert("It worked!") : alert("It didn't work.");
            }
        });
    }   

© www.soinside.com 2019 - 2024. All rights reserved.