search
HomeWeb Front-endJS TutorialTeach you how to use .Net MVC Razor syntax in Javascript files_javascript skills

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
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor