How to pass a list of objects from a java script code in a View to an action method in a controller

Viewed 108

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

2 Answers
<button onclick="myFunction()">Student Name</button>

//This is jquery which you have to include to use $ syntax. it is available //in your project directory you just check and updated this below line.

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

I'm not quite sure what you were expecting this line to do:

var studentL = @Model.ToList();

but anyway, you need to convert your model to JSON straight away, your Javascript function needs to look something like this:

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

and your Action method needs to have the following signature:

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