I do not have much experience in javascript programming. I want to pass the list of objects from a javascript code in a “View” to an action method in MVC “Controller”. Here is what I am trying to achieve –
MVC model & 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
}
}
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>
As you can see, I am passing a list of “Student” to a view called “Display”. This view has a button called “Student Name”. When that button is clicked, I want to pass the list of “Student” to the action method, “OrderStudentList” in a “StudentController” which will arrange the list in ascending/descending order. But when I run the code, I never get any value for the list in the method “OrderStudentList”.
Here is what I have tried so far for assigning the data value in above code
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”.
Nothing has worked. I will really appreciate if anyone helps. Thanks