How To Embed Razor C# Code In A .js File?
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.jsvar myFunction = function(options){
// do stuff with options
};
// razorFile.cshtml<script>window.myFunction = newmyFunction(@model.Stuff);
// If you need a whole model serialized then use...window.myFunction = newmyFunction(@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.jsvar options = $("#stuff").data('stuff');
// razorFile.cshtml<inputtype="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;
functionsomething(whatever){
}
</text>
}
You could then include it as so in your other Razor file:
<scriptsrc="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.
Solution 4:
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 heredataType: '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.
Solution 5:
And what about including a .cshtml that only contains js?
.csthml parent
@RenderPage("_scripts.cshtml")
_scripts.cshtml that contains js
<scripttype="text/javascript">alert('@Datetime.ToString()');
</script>
Post a Comment for "How To Embed Razor C# Code In A .js File?"