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

2019-01-17 23:33发布

问题:

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.

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


回答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.



回答3:

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>


回答4:

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.



回答5:

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.



回答6:

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>