Q:

How can I write a line for all my views using their view model?

I am using the following line at the beginning of all my views:
<script> var viewModel = @Html.Raw(JsonConvert.SerializeObject(Model)); </script>

I am doing that in order to manage the view model from my javascript framework but I prefer to centralize that line somehow instead of writing it in all my views, I am not sure if I can do it in a view layout since Razor does not know the view model type at that point.
How could I put that line in one single place for all my views?

A:

ViewData dictionary ( and the page Model) is available when razor executes the layout code.. So you can do this on layout.
<script>
    var mySecretApp = mySecretApp || {};       
    @if (!ViewContext.IsChildAction)
    {
        @:mySecretApp.pageViewModel = @Html.Raw(JsonConvert.SerializeObject(Model));
    }
    console.log('viewmodel', mySecretApp.pageViewModel);
</script>

