.NET Tips and Tricks

Blog archive

Controlling Model Binding in ASP.NET Core

It seems to me like magic when model binding takes data from the client and loads it correctly into the properties of the Customer object in the parameter to this method:

public ActionResult UpdateCustomer(Customer cust)
{

However, sometimes model binding doesn't do what I'd like. For example, let's say my Customer object looks like this:

public class Customer
{
  int id {get; set;}
  string FirstName {get; set;}
  string LastName {get; set;}
  int TotalOrders {get; set;}
}

If model binding can't find any data from the client to put in the LastName attribute, it will just set the property to null. I'd prefer that model binding do a little more because the typical first line of code in my method is to check for problems in model binding using the ModelState's IsValid property:

public ActionResult UpdateCustomer(Customer cust)
{
  if (!ModelState.IsValid)
  {

With model binding's default behavior, IsValid won't be set to false when there's no data for LastName.

I can get that behavior by adding the Required attribute to my Customer class' LastName property. The problem is that Required is also used by Entity Framework in code-first mode to control how the LastName column in the Customer table is declared. That probably isn't a big deal to you (though I worry about it).

Things get messier with the TotalOrders property because, unlike string properties, properties declared as integers aren't nullable. With or without the Required attribute, non-nullable datatypes are set to their default values. This means that if no data comes up from the browser for TotalOrders, it will be set to 0 ... and IsValid still won't be set to false. It's now hard to tell if the customer has no orders or if the data wasn't sent.

I could change the datatype on TotalOrders to a nullable type (that is, int?) and put the Required attribute on it ... but now I'll have to work with the TotalOrders' Value property to retrieve its data. It's all getting a little complicated.

When working with non-nullable types, I prefer using the BindRequired attribute instead of Required. BindRequired will cause model binding to set the IsValid property to false if no data comes from the client (and it will do that without affecting how my columns are declared in the database).

This is how I might declare my Customer class to get the IsValid property set when TotalOrders is missing and still have TotalOrders as a nullable column in my database:

public class Customer
{
  int? id {get; set;}
  [Required]
  string FirstName {get; set;}
  [Required]
  string LastName {get; set;}
  [BindRequired]
  int TotalOrders {get; set;}
}

If I wanted the FirstName and LastName columns to also be nullable, I'd use BindRequired on those properties, also.

Posted by Peter Vogel on 09/17/2018


comments powered by Disqus

Featured

Subscribe on YouTube