Forms and Model Binding

Intermediate 25 min read Lesson 4 of 8

Creating Forms

Basic Form

<form method="post">
    <div>
        <label>Name:</label>
        <input type="text" name="Name" />
    </div>
    <button type="submit">Submit</button>
</form>

Using Tag Helpers

<form asp-page="/Products/Create" method="post">
    <div class="form-group">
        <label asp-for="Product.Name"></label>
        <input asp-for="Product.Name" class="form-control" />
        <span asp-validation-for="Product.Name" class="text-danger"></span>
    </div>
    
    <div class="form-group">
        <label asp-for="Product.Price"></label>
        <input asp-for="Product.Price" class="form-control" />
        <span asp-validation-for="Product.Price" class="text-danger"></span>
    </div>
    
    <button type="submit" class="btn btn-primary">Create</button>
</form>

Model Binding

Simple Binding

// Pages/Products/Create.cshtml.cs
public class CreateModel : PageModel
{
    [BindProperty]
    public Product Product { get; set; }
    
    public IActionResult OnPost()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }
        // Save product
        return RedirectToPage("Index");
    }
}

Binding Specific Properties

[BindProperty(Name = "name")]
public string Name { get; set; }

[BindProperty(Name = "price")]
public decimal Price { get; set; }

Binding to Complex Objects

public class OrderViewModel
{
    public List<OrderItem> Items { get; set; }
    public string ShippingAddress { get; set; }
    public PaymentInfo Payment { get; set; }
}

[BindProperty]
public OrderViewModel Order { get; set; }

Post-Redirect-Get Pattern

public IActionResult OnPost()
{
    if (!ModelState.IsValid)
        return Page();
    
    // Process data
    TempData["Success"] = "Product created successfully!";
    
    // Redirect to avoid duplicate submission
    return RedirectToPage("Index");
}
Key Takeaway

Model binding automatically maps form data to C# objects, simplifying form handling.

Test Your Knowledge - Take Quiz