Getting Started with ASP.NET Core Razor Pages

Razor Pages is a page-focused programming model for building web UI with ASP.NET Core. It provides a simpler, file-based approach compared to MVC, making it ideal for scenarios where you have a clear separation between UI and logic.

What are Razor Pages?

Razor Pages allow you to write your UI and its associated logic in the same file, using the Razor syntax. Each Razor Page is represented by a `.cshtml` file for the UI and an optional associated `.cshtml.cs` file for the code-behind logic.

Key Concepts

Tutorial Series

1. Creating Your First Razor Page

Let's build a simple Razor Page to display a greeting.

  1. Create a new ASP.NET Core Web Application project in Visual Studio, selecting the "Razor Pages" template.
  2. Navigate to the Pages folder. You'll see files like Index.cshtml and Index.cshtml.cs.
  3. Open Index.cshtml.cs. This is your page model. Add a public property:
  4. public string Message { get; set; }
  5. In the OnGet() method, set the value of the message:
  6. public void OnGet()
    {
        Message = "Welcome to Razor Pages!";
    }
  7. Open Index.cshtml. Access the Message property within the HTML:
  8. @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    <h1>@Model.Message</h1>
    
    <p>This is your first Razor Page.</p>
  9. Run your application. You should see the "Welcome to Razor Pages!" message displayed.

2. Handling Form Submissions

Learn how to process user input from HTML forms.

We'll create a new page, Contact.cshtml, with a form to capture user details.

  1. Create a new file Pages/Contact.cshtml.
  2. Define a model for the form data in Pages/Contact.cshtml.cs:
  3. public class ContactModel : PageModel
    {
        [BindProperty]
        public string Name { get; set; }
        [BindProperty]
        public string Email { get; set; }
    
        public string ResultMessage { get; set; }
    
        public void OnGet()
        {
            // Initialize form if needed
        }
    
        public IActionResult OnPost()
        {
            if (!ModelState.IsValid)
            {
                return Page(); // Re-render the page with validation errors
            }
    
            // Process the submitted data
            ResultMessage = $"Thank you, {Name}! We have received your email: {Email}";
    
            // Clear the form or redirect
            Name = "";
            Email = "";
    
            return Page(); // Re-render the page with the result message
        }
    }
  4. Create the HTML form in Pages/Contact.cshtml:
  5. @page
    @model ContactModel
    @{
        ViewData["Title"] = "Contact Us";
    }
    
    <h1>@ViewData["Title"]</h1>
    
    <div class="row">
        <div class="col-md-6">
            <form method="post">
                <div asp-validation-summary="All" class="text-danger"></div>
                <div class="form-group">
                    <label asp-for="Name"></label>
                    <input asp-for="Name" class="form-control" />
                    <span asp-validation-for="Name" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="Email"></label>
                    <input asp-for="Email" class="form-control" />
                    <span asp-validation-for="Email" class="text-danger"></span>
                </div>
                <button type="submit" class="btn btn-primary mt-3">Submit</button>
            </form>
    
            @if (!string.IsNullOrEmpty(Model.ResultMessage))
            {
                <div class="alert alert-success mt-4" role="alert">
                    @Model.ResultMessage
                </div>
            }
        </div>
    </div>
    
    @section Scripts {
        <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
        <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
    }
  6. Ensure you have the necessary NuGet packages installed for validation: Microsoft.AspNetCore.Mvc.TagHelpers and Microsoft.AspNetCore.Mvc.NewtonsoftJson (or System.Text.Json).
  7. Run the application and navigate to the /Contact page to test the form.

Next Steps

Explore more advanced topics like:

Continue your learning journey with the official ASP.NET Core Razor Pages documentation.