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

Question

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

Answers 1
Added at 2017-01-02 19:01
Tags
Question

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?

Answers to

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

nr: #1 dodano: 2017-01-02 19:01

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>
Source Show
◀ Wstecz