I'd like to use razor syntax inside my Javascript files. Is this possible without including the javascript inline into the page?
相关问题
- Entity Framework throws exception - Network Relate
- Slow loading first page - ASP.NET MVC
- TextBoxFor decimal
- How to do an inline style with asp.net mvc 3 razor
- How to access the System.ComponentModel.DataAnnota
相关文章
- “Dynamic operations can only be performed in homog
- Change color of bars depending on value in Highcha
- How to get server path of physical path ?
- Breakpoint in ASP.NET MVC Razor view will not be h
- How to define function that returns html in asp.ne
- How to find the exceptions / errors when TryUpdate
- ASP.Net MVC 3: optgroup support in Html.DropDownLi
- A circular reference was detected while serializin
The Razor engine only runs against the page, not any included javascript files.
You could write a custom parser that will run the view engine against any javascript files before serving them, and I imagine any attempt to do so would be a very useful open source project.
However, the simplest solution that comes to mind (if these variables are not sematically linked to any DOM elements) is to simply declare and initialise your variables in the page (or in an included partial page) and your javascript (in
.js
files) relies on these variables being defined.If however the variables that you require are logically associated with DOM elements, I prefer to use
data-*
attributes to define these, this way your javascript can be consumed by the html, rather than the other way around. For example, if you have a content area that should be automatically updated by javascript (using jQuery as an example here):HTML:
Javascript:
You can set the value in hidden field in yout cshtml file , and then in your javascript files you can access the hidden field.
I found a razor engine
RazorJS
on nuget that solves@
injs
filesThe owner blog and explanations about the package abilities
The Nuget package
see more in this question