Collection Binding in Asp.et Core

Collection Binding in Asp.et Core
ASP.NET Core’s model binding isn’t limited to simple properties; it can gracefully handle collections like lists and arrays within your model classes. This is especially useful when dealing with forms that allow users to input multiple values for a single field (e.g., selecting multiple interests from a checkbox list) or when working with data from APIs that naturally return collections.
 
How Collection Binding Works
Collection Property in the Model: Your model class should have a property that’s a collection type (e.g., List<T>, T[]).
Naming Convention: The incoming request parameters should follow a specific naming convention to indicate which values belong to the collection.
Model Binder Magic: The model binder automatically recognizes the naming convention and populates the collection property accordingly.
 
Naming Conventions for Collection Binding
Indexed: items[0], items[1], items[2], … (Used for lists and arrays)
Same Name: items, items, items, … (Used for collections like ICollection<T>)
 
Code
// Person.cs (Model)
public class Person
{
    // … other properties
    public List<string?> Tags { get; set; } = new List<string?>(); // Collection property
}
 
// HomeController.cs
public IActionResult Index(Person person)
{
    // … validation and response logic …
    return Content($”Person: {person}, Tags: {string.Join(“,”, person.Tags)}”, “text/plain”);
}

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply