0

In a MVC4 app my controller does the following:

public ActionResult MyPage()
{
    var myObjects = _db.Object.ToList(); // _db is database context, object consists 
                                         // of Id and Name

    return View("MyView", 
            Json(new 
           System.Web.Script.Serialization.JavaScriptSerializer().Serialize(myObjects )));
}

Now I want to access this data and put in in the body of a table without making another call to the server, like for example the following:

$(function () {

    var result = JSON.parse(myObjects);

    for (var i = 0; i < result.length; i++) {
        renderMyObject(result[i]);
    }

    function renderMyObject(o) {

        var row = document.createElement("tr");

        var tdId= document.createElement("td");
        tdId.innerHTML = o.Id;

        var tdName = document.createElement("td");
        tdName.innerHTML = o.Name;

        row.appendChild(tdId);
        row.appendChild(tdName );

        tbody.appendChild(row);
    };
});

This does not work since result (the Model send to the view) is null. Is the above possible and if so how?

tereško
  • 58,060
  • 25
  • 98
  • 150
user2609980
  • 10,264
  • 15
  • 74
  • 143
  • possible duplicate of [How to return Json object from MVC controller to view](http://stackoverflow.com/questions/15196528/how-to-return-json-object-from-mvc-controller-to-view) – user2609980 Aug 03 '14 at 19:57

2 Answers2

1

Don't serialize in the controller, pass the model(s) to the view, and then serialize. Controller:

public ActionResult MyPage()
{
    var myObjects = _db.Object.ToList(); // _db is database context, object consists 
                                         // of Id and Name

    return View("MyView", myObjects);
}

View:

@model IEnumerable<MyProject.Models.Object>

Then use it in JavaScript to serialize etc. :

$(function(){
    var myObjects = JSON.parse(@Model);
});

If you want to use it in a separate JavaScript file, you just need to give it the correct namespace, i.e.:

var myVariable;

$(function(){
    myVariable = JSON.parse(@Model);
    initializeStuff(myVariable);
});

external JS:

var variable;

initializeStuff(stuff)
{
    variable = stuff;
}
devqon
  • 13,818
  • 2
  • 30
  • 45
  • Thanks a bunch. What if I want to place JavaScript in separate file? And 2, it does not work since the page is rendered to: `$(function () { var myObjects= JSON.parse(System.Collections.Generic.List 1[MyProject.Models.Object]);` – user2609980 Aug 01 '14 at 11:32
1

Try sending to your view a string with the JSON data model code, load it on a hidden element and just JSON.parse it on your javascript code.

Bardo
  • 2,470
  • 2
  • 24
  • 42