Welcome to our deep dive into the world of ASP.NET! Today, we're going to explore Razor Pages, a powerful feature that simplifies building web applications in ASP.NET Core. Let's get started!
In essence, Razor Pages is a page-based model that allows you to create web applications using C# and HTML. It offers an alternative to the MVC (Model-View-Controller) architecture, making it easier for beginners to grasp and understand.
A Razor Page consists of two main files:
To create a new Razor Page, right-click your project in Visual Studio and select Add > New Item. In the Search box, type Razor Page and hit Enter. Select Page and click Add. Give your page a name and click Add.
Upon creating a new Razor Page, you'll find two files: Index.cshtml and IndexModel.cs.
Index.cshtml contains the page's HTML and Razor syntax.IndexModel.cs is the C# class that contains the page's logic.using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
namespace YourNamespace.Pages
{
public class IndexModel : PageModel
{
public void OnGet()
{
// Your code here
}
}
}@{
ViewData["Title"] = "Home Page";
}
<h1>Welcome to your Razor Page!</h1>Razor syntax lets you embed C# code directly into your HTML markup. This allows for dynamic content generation and interaction with the page's data.
public class IndexModel : PageModel
{
[BindProperty]
public string UserName { get; set; }
public void OnGet()
{
}
public void OnPost()
{
UserName = HttpContext.Request.Form["UserName"].ToString();
}
}@{
ViewData["Title"] = "Home Page";
}
<h1>Welcome, @Model.UserName!</h1>
<form method="post">
<input type="text" name="UserName" placeholder="Enter your name" />
<button type="submit">Submit</button>
</form>In this example, we've created a simple form that accepts a user's name. Upon form submission, the user's name is stored in the UserName property of the page model and displayed on the page.
What is the purpose of the `OnGet` method in a Razor Page's Page Model?
That's it for today! We've covered the basics of Razor Pages and created a simple interactive page. In the next lesson, we'll dive deeper into Razor syntax and explore more advanced features of Razor Pages. Happy coding! 🎉