gpt4 book ai didi

javascript - 如何将对象列表从 View 中的 javascript 代码传递到 Controller 中的操作方法

转载 作者:行者123 更新时间:2023-11-29 15:55:24 26 4
gpt4 key购买 nike

我在 javascript 编程方面没有太多经验。我想将对象列表从“View”中的 javascript 代码传递到 MVC“Controller”中的操作方法。这是我想要实现的目标——

MVC 模型和 Controller :

 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
}
}

显示.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>

如您所见,我将“学生”列表传递给名为“显示”的 View 。该 View 有一个名为“Student Name”的按钮。单击该按钮时,我想将“Student”列表传递给“StudentController”中的操作方法“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”.

没有任何效果。如果有人提供帮助,我将不胜感激。谢谢

最佳答案

我不太确定你期望这条线做什么:

var studentL = @Model.ToList();

但无论如何,您需要立即将模型转换为 JSON,您的 Javascript 函数需要如下所示:

function myFunction() {
$.ajax({
url: "@Url.Action("OrderStudentList", "Student")",
type: "POST",
contentType: "application/json",
data: '@Html.Raw(JsonConvert.SerializeObject(Model.ToList()))',
success: function (response) {
response ? alert("It worked!") : alert("It didn't work.");
}
});
}

并且您的 Action 方法需要具有以下签名:

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

关于javascript - 如何将对象列表从 View 中的 javascript 代码传递到 Controller 中的操作方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58414734/

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