Purpose of Global - Asax
Purpose of Global - Asax
asax
In an ASP.NET MVC application, the Global.asax file (also known as the ASP.NET Application
File) is used for application-level events and configuration. It allows developers to write code
that responds to global events raised by ASP.NET or the HTTP modules.
Purpose of Global.asax:
The Global.asax file allows you to define event handlers for application-level events, such as:
The file is automatically created in ASP.NET MVC projects and is particularly useful for
performing initialization tasks when the application first loads or handling unexpected errors.
using System.Web.Mvc;
using System.Web.Routing;
1. Syntax Simplicity:
o Razor syntax is clean and concise. By using the @ symbol to transition between
HTML and C# code, Razor makes it easy to embed server-side logic directly into
HTML.
2. C# or VB.NET Embedded Code:
o The Razor engine can interpret C# (or VB.NET) expressions, loops, and
conditionals within HTML. This enables dynamic content generation based on
server-side logic.
3. Automatic Encoding:
o Razor automatically encodes HTML output to prevent injection attacks. For
example, @Model.Name will be HTML-encoded by default.
4. Intelligent Code Rendering:
o The @ symbol is used to switch from HTML to C# code, and it’s context-sensitive,
so Razor knows when to return to HTML.
<p>Hello, @Model.UserName!</p>
<p>Current year: @DateTime.Now.Year</p>
2. Code Blocks:
@{
var welcomeMessage = "Welcome to Razor!";
}
<p>@welcomeMessage</p>
3. Conditionals
@if (Model.IsLoggedIn)
{
<p>Welcome, @Model.UserName!</p>
}
else
{
<p>Please log in.</p>
}
4. Loops:
<ul>
@foreach (var item in Model.Items)
{
<li>@item.Name</li>
}
</ul>
5. Helper Methods:
Here’s a simple example of a Razor view that displays a list of items using an @model directive.
@model List<string>
<h2>Item List</h2>
<ul>
@foreach (var item in Model)
{
<li>@item</li>
}
</ul>
Lightweight and Fast: Razor views are parsed and rendered quickly.
Readable and Maintainsable: The Razor syntax is concise and easy to read.
Seamless C# Integration: Razor allows for robust C# code integration in views,
enabling logic and data processing without JavaScript or other client-side code.
In ASP.NET Core, Razor is also used to build pages in the Razor Pages framework. Razor
Pages is a page-centric model that uses Razor syntax for building web applications in a more
simplified structure than MVC.