I’m writing an MVC application and I’ve decided that Knockout.js will help with a lot of my issues, except in the process, it has created a new issue that I’m having a problem solving.
I converted all my MVC endpoints to just return views, and then I’ve created several other endpoints that returns the JSON objects. When the user browses to the website, the site loads the basic UI frame. After that, Knockout.js loads the model via AJAX calls. This has caused every page to load, and then “load” again where as with just the MVC the page loaded and all the data was present.
I’ve been looking into ways to get both to load at the same time, but I haven’t found anything that doesn’t require me to completely refactor the site. The best option was:
- Merge the JSON endpoints into the view endpoints and convert the model to JSON in the codebehind using
@Html.Raw(Json.Encode(object))
but then I have to get ride of all my pure JSON endpoints.
Is there anything else I can do to pass JSON endpoint data to the view on the serverside? Or any way to get the model and the view to load at the same time?
Your architecture is correct, but you want the initial load to pre-populate your views with data from the model. Within the controller action that just returns the Views, you should put data to populate in ViewData. Then the views are initially loaded with Model values, and each UI element can have an AJAX update that invokes the Controller action for that specific field.
This would also be an ideal case for a ViewModel. This may help as well.