How to embed Razor C# code in a .js file?

Active3 hr before
Viewed126 times

6 Answers


You can add a "section" in the cshtml view and define a variable like: variable = @Model.Parameter. And in the js file you define at the beginning of it: var Parameter; and then you can access this variable in the js file just typing Parameter there you want. – Levimatt Sep 23 '16 at 9:22 ,Connect and share knowledge within a single location that is structured and easy to search.,While I agree that you should think twice about using Razor inside your Javascript files, there is a Nuget package that can help you. It's called RazorJS., You would be much better off asking for help on a solution to the problem you are trying solve. So, start with detailing the problem, then your attempted solution. The way you are currently trying to solve it, well, is no good. – Paul Feb 23 '12 at 3:28

When I face this problem sometimes I will provide a function in the .js file that is accessible in the .cshtml file...

// someFile.js
var myFunction = function(options){
    // do stuff with options

// razorFile.cshtml
    window.myFunction = new myFunction(@model.Stuff);
    // If you need a whole model serialized then use...
    window.myFunction = new myFunction(@Html.Raw(Json.Encode(model)));

The other thing you could maybe try is using data attributes on your html elements like how jQuery.validate.unobtrusive does...

var options = $("#stuff").data('stuff');

// razorFile.cshtml
<input type="hidden" id="stuff" data-stuff="@model.Stuff" />
load more v

If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.,Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question. ,This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL),Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.

var link = '@Url.Action("ActionName", "ControllerName")'
load more v

The problem is that javascript doesn't "know" the @ symbol and doesn't parse the the C# code. Is there a way to reference .js files from view with "@" symbol?,Adding a partial view with the javascript functions to the view. This way you can use the @ symbol and all your javascript functions are separated from the view.,and then in your separate javascript file you could work unobtrusively with the DOM:,Create a JS file in your script folder and add this reference to your View

You could use HTML5 data-* attributes. Let's suppose that you want to perform some action when some DOM element such as a div is clicked. So:

<div id="foo" data-url="@Url.Content(" ~/foobar")">Click me</div>

and then in your separate javascript file you could work unobtrusively with the DOM:

$('#foo').click(function() {
   var url = $(this).data('url');
   // do something with this url
load more v

Include scripts for partial views rendered with Ajax in the partial view,Include scripts for partial views rendered with the parent view in the parent view,Note the following features of the partial view:,There are two aspects to the implementation of JavaScript with Ajax partial Razor views:

1<!DOCTYPE html>
4    <meta charset="utf-8" />
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>@ViewBag.Title - My ASP.NET Application</title>
7    @Styles.Render("~/Content/css")
8    @Scripts.Render("~/bundles/modernizr")
9    @RenderSection("header", required: false)
12    <div class="navbar navbar-inverse navbar-fixed-top">
13        <div class="container">
14            <div class="navbar-header">
15                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
16                    <span class="icon-bar"></span>
17                    <span class="icon-bar"></span>
18                    <span class="icon-bar"></span>
19                </button>
20                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
21            </div>
22            <div class="navbar-collapse collapse">
23                <ul class="nav navbar-nav">
24                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
25                    <li>@Html.ActionLink("About", "About", "Home")</li>
26                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
27                </ul>
28            </div>
29        </div>
30    </div>
31    <div class="container body-content">
32        @RenderBody()
33        <hr />
34        <footer>
35            <p>@DateTime.Now.Year - My ASP.NET Application</p>
36        </footer>
37    </div>
39    @Scripts.Render("~/bundles/jquery")
40    @Scripts.Render("~/bundles/bootstrap")
41    @RenderSection("scripts", required: false)
load more v

Now if you call e.g. /JavaScript/config.js, the Config action will be called and the result will be returned transparently as JS file.,It’s pretty the same for CSS. You just need a custom CSS output method in the ControllerExtentions class:,This method resolves a given view, gets it compiled and returned as string and removes the script Tags. The result is returned with the correct content type. You can call it in your controller with:, ASP.NET Core/IIS: serving content from a file share

Now unfortunately (or not) you cannot put Razor syntax in plain *.js files, because they are static content and not touched by the compiler. But you can create a *.cshtml-file, that is returned as *.js-file to the client after compilation. The easiest way how to do this is with a custom route. Say, every action in a JavaScriptController should return a *.js file, then you could use the following setup in your MVC6 Startup class:

app.UseMvc(routes => {
      name: "javascript",
      template: "JavaScript/{action}.js",
      defaults: new {
         controller = "JavaScript"
load more v

In the following example:,Add parameters to the .NET method invocation. In the following example, a name is passed to the method. Add additional parameters to the list as needed.,For the following CallDotNetExample2 component:,In the preceding example:

ReturnArrayAsync method composed with async and await keywords:

public static async Task<int[]> ReturnArrayAsync()
    return await Task.FromResult(new int[] { 1, 2, 3 });
load more v

Other "undefined-undefined" queries related to "How to embed Razor C# code in a .js file?"