You are currently viewing Beginner’s Guide to ASP.NET Razor: Understanding Syntax and Examples

Beginner’s Guide to ASP.NET Razor: Understanding Syntax and Examples

Introduction to ASP.NET Razor

ASP.NET Razor is a server-side markup language that allows you to seamlessly integrate server-side code with HTML to create dynamic web pages. In this tutorial, we’ll explore the basics of ASP.NET Razor syntax and demonstrate its usage with code examples.

Getting Started

Before diving into ASP.NET Razor, ensure you have Visual Studio installed on your system. Let’s create a new ASP.NET Web Application project to get started.

Step 1: Create a New ASP.NET Web Application

Open Visual Studio and select “Create a new project.” Choose “ASP.NET Web Application” and provide a name for your project.

Step 2: Select Project Template

Select the “Web Application (Model-View-Controller)” template and click “Create.”

Step 3: Understanding Razor Syntax

ASP.NET Razor syntax allows you to embed C# code directly into HTML markup using special Razor syntax.

Example 1: Displaying Current Date

<p>Today's date is: @DateTime.Now.ToShortDateString()</p>

In the above example, @DateTime.Now.ToShortDateString() is Razor syntax that executes C# code to get the current date.

Example 2: Looping Through Data

<ul>
    @foreach (var item in Model.Items)
    {
        <li>@item.Name</li>
    }
</ul>

In this example, we use Razor syntax to iterate through a collection (Model.Items) and display each item’s name.

Step 4: Razor Layouts and Partial Views

Razor layouts and partial views help maintain a consistent UI across multiple pages.

Example 3: Creating a Layout

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
</head>
<body>
    <header>
        <h1>Welcome to my website!</h1>
    </header>

    <div id="content">
        @RenderBody()
    </div>

    <footer>
        <p>© 2024 My Website</p>
    </footer>
</body>
</html>

In this example, @RenderBody() renders the content of the child views within the layout.

Step 5: Razor Helpers

Razor helpers simplify common tasks like form creation, URL generation, and more.

Example 4: Form Creation

@using (Html.BeginForm("Action", "Controller", FormMethod.Post))
{
    @Html.TextBoxFor(model => model.Name)
    <button type="submit">Submit</button>
}

Here, Html.BeginForm and Html.TextBoxFor are Razor helpers for creating HTML forms and input fields.

Conclusion

ASP.NET Razor provides a powerful way to create dynamic web applications with C# and HTML. In this tutorial, we’ve covered the basics of Razor syntax, layouts, partial views, and helpers. Experiment with these concepts to build your own interactive web applications. Happy coding!

Leave a Reply