user2609980
user2609980

Reputation: 10484

Send a JSON object to view and access it on the page

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?

Upvotes: 0

Views: 516

Answers (2)

devqon
devqon

Reputation: 13997

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

Upvotes: 1

Bardo
Bardo

Reputation: 2523

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.

Upvotes: 1

Related Questions