Craig Craig - 3 months ago 23
HTML Question

Access to Model parameter in .js file

I am moving all my javascript out of my views, and into separate .js files. But I am facing one issue.

Some javascript references a model parameter:

var data = @Html.Raw(Model.RunningTotalData)

@Html, and probably Model... isn't available in the js files.

One solution might be, in the that the code is working with, create a data- type field? And populate it on the view, and then the js code somehow reads that data?

At the moment, the js is rendering a graph on a div, defined as:

<div id="allbalancediv" style="width: 100%;"></div>

Could I add a data-xxx there, and then refer to that data field in my js code? I'm not sure if that's the right way to go, or if there's a better option.


You obviously can't render server side content into static javascript files. But you can still render a script tag that sets up data for your JS files.

// View
<script>var data = @Html.Raw(Model.RunningTotalData)</script>
<script src="/frontend.js"></script>

Or a data attribute that gives your JS code an id to fetch via AJAX from a JSON api would work too.