Reputation: 95
I'm trying to send data from controller to Knockoutjs using a dictionary as explained here: Sending and Recieving Data between ASP.NET MVC and Knockout.js but I don't understand which attribute I should pass to serialize.Serialize (????) and how to get the ViewBag.myData in knockoutjs file.
Question1:
Which object should I use here?:
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var Data = new Dictionary<String, Object>()
{
{"objName1", _objName1Service.GetAsync().Result},
{"objName2", _objName2Service.GetAsync().Result},
};
ViewBag.myData = serializer.Serialize(????);
Question2:
What is the equivalent of this instruction in Knockout.js?
var myData = @Html.Raw(ViewBag.myData);
Upvotes: 0
Views: 518
Reputation: 11990
Serialize your object using some library, like Json.NET (as recommended by Rob G).
string output = JsonConvert.SerializeObject(yourObject);
Send your json object to the View, using ViewBag
ViewBag.YourJsonObject = output;
Print the json object to an html hidden field
<input type="hidden" id="myHiddenField" value="@ViewBag.YourJsonObject" />
Use the html hidden field to set knockout's observable
var myData = ko.observable($('#myHiddenField').val());
Upvotes: 1