mishi caro
mishi caro

Reputation: 23

how to send generic list with json

I have generic list to view.

List<Student> StudentList = ViewBag.StudentList;

I want send this list with JSON.

var listSTD = @StudentList;
var id = 5;
    $.ajax({
        url: "/Students/Check",
        type: "POST",
        dataType: 'json',
        data: {"listSTD": listSTD, "id": id},
        contentType: "application/json; charset=utf-8",
        success: function(result) {
            alert(result.Result);
        }
    });

but is not working. get error in this code:

var listSTD = @StudentList;

Upvotes: 0

Views: 631

Answers (2)

kyleruss
kyleruss

Reputation: 497

You shouldn't be passing the List<Student object directly to your script as the object is not in a format js can read or work with so you need to JSON serialize the object into a JSON string which you can then include in the data body of your post request.

You can serialize the object with Newtonsoft.Json and you need to make sure the listSTD variable is instantiated inline when the view is rendered rather than in an external file (the rest of your code can be in an external js file). For example:

<html>
  <body>
    @{ List<Student> StudentList = ViewBag.StudentList; }

    <script>
       var listSTD = "@JsonConvert.SerializeObject(StudentList)";
    </script>
  </body>
<html>

On the server-side controller action responding to your post request at /Students/Check you can de-serialize the posted student list JSON back into List<Student> For example in your controller action:

public class StudentsController
{
  public ActionResult Check(StudentsCheckViewModel model)
  {
     int id = model.id;
     List<Student> Students = Json.DeserializeObject<List<Student>>(model.listSTD);
  }
}

And the view model:

public class StudentsCheckViewModel 
{
   public int id { get; set; }

   public string listSTD { get; set; }
}

Upvotes: 1

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131523

You can serialize the data as JSON into the view using the JSON helper, eg :

<script type="text/javascript" charset="utf-8">

    var rowData = @Json.Serialize(Model.Rows);
    ...

</script>

In older versions you may have to use Json.Encode or wrap the call in Html.Raw, eg @Html.Raw(Json.Serialize(...))

Upvotes: 0

Related Questions