简体   繁体   中英

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

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.

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" />

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>

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.

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.

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.

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>

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>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM