Razor example in an ASP.NET
Here's a basic example of using Razor syntax within an ASP.NET Core application to illustrate how Razor integrates server-side C# code with HTML markup:
Example: Creating a Razor View in ASP.NET Core
- Create a Razor View
In an ASP.NET Core project, typically under the Views
folder, create a new Razor view file with the extension .cshtml
. For example, Index.cshtml
.
<!-- Index.cshtml -->
@page
@model MyApp.Pages.IndexModel
@{
ViewData["Title"] = "Home";
}
<h1>Welcome to Razor Pages!</h1>
<p>Hello, @Model.UserName!</p>
<ul>
@foreach (var item in Model.Items)
{
<li>@item.Name - @item.Description</li>
}
</ul>
- Explanation of the Razor Example
@page
: Specifies that this Razor page will handle HTTP GET requests.@model MyApp.Pages.IndexModel
: Specifies the strongly-typed model (IndexModel
) for this Razor page.@{ ... }
: Code block where you can write C# code to execute server-side logic or set variables.@ViewData["Title"]
: Sets the title of the page.@Model.UserName
: Accesses theUserName
property from theIndexModel
.@foreach (var item in Model.Items) { ... }
: Iterates over a collection (Items
inIndexModel
) and renders HTML for each item.
- Using Razor in ASP.NET Core
- Razor enables mixing HTML markup with C# code seamlessly, making it easy to generate dynamic content based on server-side data.
- The example above demonstrates basic usage, including setting the page title, accessing model data (
UserName
andItems
), and iterating over a collection to render a list.
- Integration with ASP.NET Core
- Razor pages (
cshtml
files) are part of ASP.NET Core's MVC framework and can utilize features like routing, model binding, and dependency injection. - Razor promotes clean separation of concerns by keeping presentation logic separate from backend logic, enhancing maintainability and code readability.
This example showcases how Razor simplifies the process of creating dynamic web pages in ASP.NET Core by seamlessly integrating server-side C# code with HTML, facilitating efficient and maintainable web application development.
Published on: Jul 01, 2024, 09:30 AM