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

32,745

Solution 1

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
<script>
    window.myFunction = new myFunction(@model.Stuff);
    // If you need a whole model serialized then use...
    window.myFunction = new myFunction(@Html.Raw(Json.Encode(model)));
</script>

Not necessarily the BEST option, but it'll do if you have to do it...

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

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

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

Solution 2

Here's a sample Razor webpage (not an MVC view, although that would be similar) that will serve Javascript. Of course, it's atypical to dynamically write Javascript files, but here's a sample nonetheless. I used this once in a case where I wished to provide JSON data and some other stuff that was expensive to compute and changed rarely - so the browser could include it and cache it like a regular JS file. The trick here is just to set the Response.ContentType and then use something like the Razor <text> tags for your Javascript.

@{
Response.ContentType = "text/javascript";
Response.Cache.SetLastModified(System.Diagnostics.Process.GetCurrentProcess().StartTime);
Response.Cache.SetExpires(System.DateTime.Now.Date.AddHours(28));
Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
<text>
var someJavaScriptData = @someSortOfObjectConvertedToJSON;
function something(whatever){
}
</text>
}

You could then include it as so in your other Razor file:

<script src="MyRazorJavascriptFile.cshtml"></script>

Solution 3

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.

The author of the package has a blog post about it, that explains how to use it.

Share:
32,745
Kenet Jervet
Author by

Kenet Jervet

Updated on July 09, 2022

Comments

  • Kenet Jervet
    Kenet Jervet almost 2 years

    Have to embed javascript code block with

    <script type='text/javascript'>
      ...
    </script>
    

    But Razor code won't compile in a .js file, included from a .cshtml file.

    How to make this work? Or is there any other elegant way to have a similar effect?

    Thank you.

  • RPM1984
    RPM1984 about 12 years
    +1, i go with setting variables/js objects in the view as well. Commonly this is the case for URL's that need to be accessed via ajax. E.g <script>var ajaxUrl = '@Url.Action('Blah", "Blah", new { id = Model.Id});</script>
  • mdance
    mdance about 10 years
    I like his second option. It is a little bit odd, but it works.
  • Levimatt
    Levimatt over 7 years
    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.