I currently use Knockout to dynamically load data once a page has loaded. I'm using Controller methods, like:
public JsonResult GetData(int paramId)
{
return Json(new { Field1: true });
}
This is then called like (in JS):
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/Dashboard/GetData',
data: JSON.stringify({ paramId: valId }),
dataType: "json",
error: function (xhr, ajaxOptions, thrownError) {
},
success: function (data) {
var val = data.Field1;
}
});
Here, the data object is an already JS accessible object.
This approach is nice when I want to refresh individual items, but it makes the initial load fairly inefficient - there are a number of calls that need to be made to initialize the page.
In my ActionResult method to load the View, I'd like to call GetData() and return it's result in a way that matches the data value in the ajax call referenced above.
How can I achieve something like this? I assume I'd need to add the result of the call to my model for the View, and then assign the value to a JS variable in the View.
Something like:
public ActionResult Index() {
var iModel = new IndexModel();
iModel.DataResults = GetData();
return View(iModel);
}
Then in the view itself, something like:
var dataHolder = @Model.DataResults;
This doesn't work, I just get a naming of the type, not the actual data as it would exist in the data variable inside the ajax call.
How can I achieve this?