I’ve struggled with this limitation since the first preview release of ASP.NET MVC. Here are a couple of the approaches that I tried (and hated):
Place scripts in partial views
The downside to this approach is that the script cannot be easily minimized or combined, and it can’t be cached by the browser since it is actually rendered inline in the final markup produced by the view.
Pass view model properties through an initialization function
This approach is also less than ideal. Any values the script requires must be manually extracted from the view model, which makes maintenance more of a headache than it should be.
The ideal solution
The above code block should appear before any scripts that wish to access properties from the view model, which can reference view model properties easily:
This is a big improvement over the other two approaches I’ve tried (at least in my opinion), but it still requires me to perform this mundane serialization task on each view. An easy improvement is to move it to the master page:
Now every view that has a view model will automatically have a Model object available.
Thoughts? Suggestions? Anyone found a better solution that I’ve just overlooked somehow?