alex
alex

Reputation: 7453

Casting MVC ViewModel to Javascript object in external .js file

As a corollary to this question, I know it's possible to represent cast an MVC ViewModel object to Javascript using some technique like var jsObject = @Html.Raw(Json.Encode(Model)).

I'm assuming it's only possible to use this technique directly on the actual .cshtml page. What if I wanted to us this data in an external .js file?

If I instantiated var jsObject on the .cshtml page, could I still access this object from an external Javascript file, or would it be considered to be out-of-scope?

Upvotes: 2

Views: 2303

Answers (1)

Andy T
Andy T

Reputation: 9891

You could access the generated jsObject from within your javascript file. In order for it to not be out of scope, you need to treat it like a global:

In your `.cshtml':

var jsObject = @Html.Raw(Json.Encode(Model))
<script src="/path/to/jsFile.js">

Inside your jsFile.js

if(jsObject)
{
 // do whatever you need
}

Notice that since you are not passing in the variable to a method in jsFile.js the only way for jsFile.js to get access to it is by knowing what name you gave it in your .cshtml. This makes your code very brittle. The other, better approach, is to pass in the variable to your JavaScript function.

In your .cshtml:

<script src="/path/to/jsFile.js">

var jsObject = @Html.Raw(Json.Encode(Model))
myProcessor(jsObject)

Using this approach, the myProcessor method doesn't care what the name of your variable is.

Upvotes: 3

Related Questions