2

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?

4
  • Use RazorJS Commented Apr 5, 2016 at 15:35
  • Create Action and call it using jQuery ajax. Commented Apr 5, 2016 at 15:36
  • @Brij I'm looking for a way to do this without making another round-trip to the server. Also, RazorJS doesn't look like it's maintained (its website is down) and I'm not looking to use C#-style syntax in my Javascript files. Commented Apr 5, 2016 at 15:40
  • you would like to see techbrij.com/pass-session-viewbag-values-js-file-asp-net-mvc Commented Apr 5, 2016 at 15:44

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.