How to use the.Net MVC Razor syntax in Javascript files

  • 2020-03-30 03:36:18
  • OfStack

I'm sure you've all tried nesting javascript within a View, so you can use Razor syntax directly to call some.net methods. The following code is nested in a Razor's View:


<script>
 var currDate = '@DateTime.Now'; //Call.net methods directly
 
 console.log(currDate)
</script>

But the other thing is, if I want to use Razor in a separate JS file, that's not going to work, because MVC is not going to directly explain the JS file, it's only going to work in the Razor view. However, I recommend a third-party library that lets you use Razor directly in a standalone JS file


This library is called RazorJS. It is an open source project and can be downloaded from the following address:

(link: https://bitbucket.org/djsolid/razorjs)

Or you can install it directly through Nuget:


PM> Install-Package RazorJS

After running, you can directly get all the contents in the web.config file in JS. Looks pretty good, huh? So how exactly do such libraries work? It does this using a library called RazorEngine. RazorEngine is a Razor interpretation engine that is very powerful and I have used it on several projects before. With this engine, you can even use Razor syntax directly in Windows form.

Well, yes, with this engine, you can completely separate your web environment to use MVC's Razor, which allows you to easily create flexible templates, such as email templates, where you can directly use various.net methods or even custom objects, and then dynamically generate the content you want. OK, but this engine is not what I'm going to introduce this time, just by the way

Next, a RazorJS use method, if you are directly through the Nuget installation, then will automatically help you configure the web. Config, this is the recommended installation method, otherwise you will have to add their own web. To use RazorJS, you simply use the following syntax to refer to the JS file you want:


<p>
 @Html.RazorJSInline("~/Scripts/Example.js")
</p>

Note, however, that there is a section of your web.config configuration that allows RazorJS to use a directory, meaning that your JS files must be in this directory to be referenced using this method:


<razorJSSettings handlerPath="~/razorjs.axd">
 <allowedPaths>
 <add path="~/Scripts" />
 </allowedPaths>
 </razorJSSettings>

The last thing I want to talk about is the limitations. There are good things and there are bad things, because it USES RazorEngine, so you can't use the MVC HTML Helper method in JS, which is all the @html methods. Another problem is that it doesn't recognize the comment code in JS, which means that if you use the.net method in the comment, it will be executed as well. If your method is correct, it will be fine, otherwise it will interrupt the execution of JS and directly report an error, so don't think you can comment out the unused method.

Here's another solution to the problem of not being able to perform the @html helper, but you can modify the source code for those who want to play around with it. In fact, this can also use a lot of custom methods, more flexible and convenient oh. After downloading the RazorJS source code, you can modify it directly and then recompile a DLL. Another way is to add the source code to your own project as if it were another project.

In its source, open the htmltemplatebase.cs file, you can add your own methods here, and then here to add methods can be directly called in JS. If you find an Href method encapsulated in the source code, you can convert the URL to one that is available on the requesting client. According to this method, we can add our own methods, such as the following is my encapsulation of a dynamic method to obtain internationalization resource files, so that we can directly use.net resource files in JS internationalization:


public class HtmlTemplateBase : TemplateBase
 {
 //Manually invoke the resource file manager
 private static ResourceManager resources = (ResourceManager)System.Type.GetType
  ("RazorJS.Resource").GetProperty("ResourceManager").GetValue(null, null);
 
 public HtmlTemplateBase()
 {
  Url = new UrlHelper(HttpContext.Current.Request.RequestContext);
 }
 public string Href(string originalUrl)
 {
  return Extensions.ResolveUrl(originalUrl);
 }
 
 public string GetLangText(string langKey)
 {
   According to the key Returns the relevant language 
  return resources.GetString(langKey);
 }
 
 public UrlHelper Url { get; set; }
 }

Then call it directly in JS:


var s = '@GetLangText("CoderBlog")';
console.log(s);

After running, you can directly enter the content of the key CoderBlog in JS


Related articles: