Explore practical examples of data binding in ASP.NET Core, covering both MVC and Razor Pages. This documentation showcases various techniques to efficiently transfer data between your client-side and server-side code.
Data binding is a core concept that simplifies the process of updating the UI based on data and vice versa. In ASP.NET Core, it's fundamental for creating dynamic and interactive web applications.
Demonstrates how form elements automatically bind to properties of a model passed to the controller action.
public class UserController : Controller { public IActionResult Register() { return View(); } [HttpPost] public IActionResult Register(UserViewModel model) { if (ModelState.IsValid) { // Process the valid model data return RedirectToAction("Success"); } return View(model); // Redisplay the form with validation errors } } public class UserViewModel { public string Username { get; set; } public string Email { get; set; } [Required] public string Password { get; set; } }
@model UserViewModel@section Scripts { }
Razor Pages streamline page-focused development. Data binding works similarly to MVC but is integrated directly into the PageModel.
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using System.ComponentModel.DataAnnotations; public class InputModel : PageModel { [BindProperty] public string Message { get; set; } [BindProperty] [Required] [EmailAddress] public string UserEmail { get; set; } public void OnGet() { // Initialization logic if any } public IActionResult OnPost() { if (!ModelState.IsValid) { return Page(); // Redisplay the page with validation errors } // Process the bound data (Message, UserEmail) return RedirectToPage("./Success", new { email = UserEmail }); } }
@page @model InputModel @{ ViewData["Title"] = "Input Page"; }@section Scripts {Data Input
Handles scenarios where you need to bind to lists or arrays of data, common in forms for multiple items.
Binding to nested objects within your models.
For scenarios where default model binding isn't sufficient, allowing you to create custom logic for transforming incoming data.
Using JavaScript (e.g., jQuery or Fetch API) to send data to server endpoints and receiving JSON responses.