Model binding is powerful, but sometimes you want more granular control over which properties get populated from incoming request data. This is where [Bind] and [BindNever] come in.
[Bind] Attribute Purpose: Explicitly include specific properties for model binding. Usage: Apply this attribute to your action method parameter (e.g., the model class) and provide a list of property names as arguments. Example: [HttpPost] public IActionResult Create([Bind(“Title”, “Description”)] Product product) { // Only the Title and Description properties will be bound from the request. } In this example, even if the incoming request contains data for other properties of the Product class (like Price or Category), they will be ignored during model binding.
[BindNever] Attribute Purpose: Exclude specific properties from model binding. Usage: Apply this attribute directly to model properties that you never want to be bound from the request. Example: public class Product { // … other properties
[BindNever] public DateTime CreatedAt { get; set; } // Never bind from request } In this example, the CreatedAt property will always retain its default value, regardless of whether the incoming request contains data for it.
Code // Person.cs (Model) public class Person : IValidatableObject { // … (other properties)
[BindNever] // This property will not be bound during model binding public DateTime? DateOfBirth { get; set; }
// … (other properties and methods) … }
// HomeController.cs [Route(“register”)] public IActionResult Index(Person person) { // … (validation and response logic) … } In this code: DateOfBirth (BindNever): The [BindNever] attribute on the DateOfBirth property tells the model binder to completely ignore any data for this property coming from the request. Even if the incoming request contains a value for DateOfBirth, it won’t be assigned to the model property.