When working in the .Net MVC environment, developers have easy access to model data at the view level and can utilize Razor syntax effectively for operations like iterating through lists. However, when introducing a JavaScript framework like AngularJS, a shift in data access strategies is necessary:
- Switch to RESTful requests for all data retrieval, consuming JSON data through Angular factories.
- Consider views as simple templates for displaying data.
- Keep JavaScript code separate in individual files following SOLID principles.
While this approach may work well with AngularJS, I encountered a scenario where Knockout was introduced late into an enterprise-level MVC3 project. In this case, the view contained DTO/ViewModel data alongside Knockout data-bound controls, pulled from RESTful requests, leading to mixed JavaScript and Razor code within *.cshtml files.
An issue arose when a new feature required presenting data in a list. Initially, I added a new data structure to the model data assuming it would be included in the RESTful response. However, I found that it was only accessible as @model data in the MVC view. This resulted in having both a RESTful response and MVC model (view model) data on the view.
Instead of complicating the process by converting data to JSON and performing Knockout data binding, I realized using Razor syntax provided a more straightforward solution to achieve the same outcome.
This situation also prompts consideration for utilizing MVC model data in JS frameworks while maintaining proper separation of concerns without mixing JS code in the view.
Moving forward, I aim to avoid hybrid data access methods and seek clarity on whether combining these approaches is a common practice due to lack of planning or for other reasons.
Thank you.