Is it possible to access a Model property in an external Javascript file?
e.g. In \"somescript.js\" file
var currency = \'@Model.Currency\';
alert(cu
I tackled this problem using data attributes, along with jQuery. It makes for very readable code, and without the need of partial views or running static javascript through a ViewEngine. The JavaScript file is entirely static and will be cached normally.
Index.cshtml:
@model Namespace.ViewModels.HomeIndexViewModel
Index
@section scripts
{
}
Index.js:
jQuery(document).ready(function ($) {
// import all the variables from the model
var $vars = $('#Index\\.js').data();
alert($vars.page);
alert($vars.actionUrl); // Note: hyphenated names become camelCased
});
_Layout.cshtml (optional, but good habit):
@Scripts.Render("~/bundles/js")
@RenderSection("scripts", required: false)