Access a Model property in a javascript file?
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
<h2>
Index
</h2>
@section scripts
{
<script id="Index.js" src="~/Path/To/Index.js"
data-action-url="@Url.Action("GridData")"
data-relative-url="@Url.Content("~/Content/Images/background.png")"
data-sort-by="@Model.SortBy
data-sort-order="@Model.SortOrder
data-page="@ViewData["Page"]"
data-rows="@ViewData["Rows"]"></script>
}
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):
<body>
<!-- html content here. scripts go to bottom of body -->
@Scripts.Render("~/bundles/js")
@RenderSection("scripts", required: false)
</body>
What you could do is passing the razor tags in as a variable.
In razor File>
var currency = '@Model.Currency';
doAlert(currency);
in JS file >
function doAlert(curr){
alert(curr);
}
There is no way to implement MVC / Razor code in JS files.
You should set variable data in your HTML (in the .cshtml files), and this is conceptually OK and does not violate separation of concerns (Server-generated HTML vs. client script code) because if you think about it, these variable values are a server concern.
Take a look at this (partial but nice) workaround: Using Inline C# inside Javascript File in MVC Framework