17

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.

3
  • 1
    ... People that dynamically generate JavaScript suffer horribly. You don't embed Razor code in a javascript file because JAVASCRIPT FILES ARE STATIC. Commented Feb 23, 2012 at 3:18
  • 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. Commented Feb 23, 2012 at 3:28
  • I would try to find a more general solution or else I would need to ask here many times for different situations. Commented Feb 23, 2012 at 10:09

7 Answers 7

27

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" />
Sign up to request clarification or add additional context in comments.

3 Comments

+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>
I like his second option. It is a little bit odd, but it works.
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.
5

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>

Comments

2

You can't. Nor should you even try. Keep them separate. This goes for the other way around, but you should look into Unobtrusive JavaScript. That design pattern applied throughout the project is a great idea.

1 Comment

I did try Unobtrusive JavaScript, but in some circumstances I would need to update different elements, or update a parent element which might be retrieved using a jQuery statement $('#bla').parent(), or just act variously according to Response. I may not have digged deep into it, but AFAIK it can't meet my need.
0

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.

1 Comment

This has been deprecated now
0

Maybe I can provide a useful work-around, depending on what you wish to accomplish.

I was tempted to find a way to evaluate razor expressions in a java script file. I wanted to attach a jQuery click event handler to submits with a specific class that are found on many pages. This should be done in a jQuery document ready event handler. This click event would perform an ajax call.

The url of these should be application relative, not absolute, in case the application lives below the root level. So, I wanted to use something like

$(document).ready(function () {
    $('input[type="submit"].checkit)').click(function (e) {
        $.ajax({
            type: 'POST',
            url: '@Url.Content("~/checkit")', //Razor expression here
            dataType: 'json',
            success: function (data) {
                if (!data) {
                    e.preventDefault();
                    handleResponse(data);
                }
            },
            data: null,
            async: false
        });
    });
});

I solved this by wrapping the code in a function Checkit and moving the call to the layout view:

        $(document).ready(function () {
            Checkit('@Url.Content("~/checkit")');
        });

Most of the javascript code is still in a javascript file.

Comments

0

And what about including a .cshtml that only contains js?

.csthml parent

@RenderPage("_scripts.cshtml")

_scripts.cshtml that contains js

<script type="text/javascript">
alert('@Datetime.ToString()');
</script>

Comments

0

If your goal is to apply/fire valid JS code as per user role then you can do the following:

  1. Create partial view in Views/Shared/js folder.

    Here js folder is created by me manually. You can give any name.

  2. Then add layout page(partial view) with prefix _ sign.

    Here I create _mypageScrtipts.cshtml

  3. Move your JS file code into _mypageScrtipts.cshtml and put role condition and fire JS code according to it.

Example:

@{var role = User.Identity.GetRole();} //came from "AspNetRoles" table

@if(role=="Admin") 
{
  <script> alert("I am admin user."); </script>
}
else
{
  <script>alert("I am normal user.");</script>
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.