How to Import a Namespace in Razor View Page with example

Razor View Pages in ASP.NET MVC allow you to create dynamic web pages with the combination of HTML and C# code. Importing namespaces in Razor View Pages enables you to access classes and methods defined within those namespaces without fully qualifying them. This tutorial will guide you through the process of importing a namespace in a Razor View Page with code examples.

Step 1: Open the Razor View Page

Navigate to the Razor View Page where you want to import the namespace. This could be a .cshtml file within your ASP.NET MVC project.

Step 2: Import the Namespace

To import a namespace in a Razor View Page, you can use the @using directive at the top of the file. This directive informs the Razor engine to import the specified namespace for use within the page.

@using YourNamespace

Replace YourNamespace with the namespace you want to import.

Step 3: Access Types and Methods

Once you've imported the namespace, you can directly access types, classes, and methods defined within that namespace within the Razor View Page without fully qualifying them.

@{
    var instance = new YourClass(); // No need to fully qualify YourClass
    var result = instance.YourMethod(); // No need to fully qualify YourMethod
}

Example

Suppose you have a namespace named MyApp.Utilities containing a class named StringHelper with a method Capitalize that capitalizes the first letter of a string. Here's how you would import and use this namespace in a Razor View Page:

@using MyApp.Utilities

<!DOCTYPE html>
<html>
<head>
    <title>Example Razor Page</title>
</head>
<body>
    <div>
        @{
            var inputString = "hello world";
            var capitalizedString = StringHelper.Capitalize(inputString);
        }

        <p>Original String: @inputString</p>
        <p>Capitalized String: @capitalizedString</p>
    </div>
</body>
</html>

In this example, the MyApp.Utilities namespace is imported using @using directive at the top of the Razor View Page. Then, the StringHelper class and its Capitalize method are used directly without fully qualifying them.

Importing namespaces in Razor View Pages is a straightforward process using the @using directive. It allows you to access classes and methods defined within the imported namespaces without fully qualifying them, enhancing code readability and maintainability in your ASP.NET MVC projects.

 
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice