Home  >  Article  >  Web Front-end  >  Teach you how to use .Net MVC Razor syntax in Javascript files_javascript skills

Teach you how to use .Net MVC Razor syntax in Javascript files_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:41:182033browse

I believe everyone has tried nesting javascript in a View. At this time, you can directly use Razor syntax to call some .NET methods. For example, the following code is nested in a Razor View:

<script>
 var currDate = '@DateTime.Now'; //直接调用.NET的方法
 
 console.log(currDate)
</script>

But another situation is that if I want to use Razor in an independent JS file, then the above method is not feasible, because MVC will not directly interpret the JS file and can only be placed in the Razor view. But here I recommend a third-party library that allows you to use Razor directly in a stand-alone JS file


The name of this kind of library is RazorJS. This is an open source project. You can download the source code at the following address:

https://bitbucket.org/djsolid/razorjs

Or you can install it directly through Nuget:

PM> Install-Package RazorJS

OK, let’s first talk about what this class library can bring us. After installation, you can use all .NET supported methods directly in JS files. For example, the above code can be directly put into a separate JS file for use. In addition, you can also reference the full namespace of .NET in the JS file. If you want to call the File object to read the content of the text file, you can directly reference the System.IO namespace:

@using System.IO;
 
var s = 'Hello at @DateTime.Now \n @File.ReadAllText(System.Web.Hosting.HostingEnvironment.MapPath("~/web.config"))';

After running, you can get all the contents in the web.config file directly in JS. It looks pretty good, haha. So how do such libraries work? In fact, it uses a class library called RazorEngine to achieve the above effects. RazorEngine is a Razor interpretation engine that is very powerful and I have used it in some projects before. Through this engine, you can even use Razor syntax directly in win forms. Haha, have you ever thought of its benefits?

Well, that’s good. With this engine, you can use MVC’s Razor completely independent of the web environment. This feature allows you to easily create some flexible templates, such as some email templates. You can directly create them in the template. Use various .NET methods or even custom objects and dynamically generate what you want. OK, but this engine is not what I want to introduce this time. I’m just talking about it here

Next, let’s talk about how to use RazorJS. If you install it directly through Nuget, it will automatically configure web.config for you. This is the recommended installation method, otherwise you have to add it yourself to web.config. There are several places in the configuration, which are not detailed here. You can compare them after you install them. To use RazorJS is also very simple, just use the following syntax to reference the JS file you want:

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

But one thing to note is that in your web.config there will be a directory configured to allow RazorJS to be used, which means that your JS files must be placed in this directory before they can be referenced using this method:

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

The last thing I want to talk about is its limitations. Of course there are good points but also bad aspects. Since it uses RazorEngine, you cannot use MVC's HTML Helper methods in JS, that is, all methods starting with @Html. Another problem is that it cannot recognize the comment code in JS. That is to say, if you use .NET methods in comments, it will still be executed. If your method is correct, there will be no problem. Otherwise, the execution of JS will be interrupted and an error will be reported directly. , so don’t think that just commenting out useless methods is enough.

Regarding the problem of not being able to execute @Html helper, I provide another solution here, but this can modify its source code. Friends who want to mess with it can try it. In fact, you can also use many customized methods to do this, which is more flexible and convenient. After downloading the RazorJS source code, you can directly modify it and recompile a DLL. Another method is to treat its source code as another project and add it directly to your own project.

In its source code, open the HtmlTemplateBase.cs file, you can add your own methods here, and then the methods added here can be called directly in JS. For example, in the source code you can find an encapsulated Href method that converts the URL into a URL available on the requesting client. According to this writing method, we can add our own methods. For example, the following is how I encapsulate a method of dynamically obtaining internationalized resource files, so that .NET resource files can be used directly in JS for internationalization:

public class HtmlTemplateBase : TemplateBase
 {
 //手工调用资源文件管理器
 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)
 {
  根据key返回相关的语言
  return resources.GetString(langKey);
 }
 
 public UrlHelper Url { get; set; }
 }

Then just call it directly in JS:

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

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn