]> MVC5 Complex model binding with Dictionaries 🌐:aligrant.com

MVC5 Complex model binding with Dictionaries

Alastair Grant | Tuesday 16 February 2016

There are a few references to Scott Hanselman's blog on model binding. It covers mapping from an HTML form to complex objects in the .NET controller with MVC.

I suspect things have moved on since this was written so I thought I'd point out how much easier it is now.

If you want a Dictionary of complex objects as a result of your form posting (e.g.a multi-record sort of affair) then languages such as PHP offer this up easily with associative arrays. Luckily MVC 5's model binder does a similar job:

Let's consider this C#

public class Company {
  public string CompanyName { get; set; }
  public bool? Active { get; set; }
}

public ActionResult UpdateCompany(Dictionary<string, company=""> companies) {
  foreach(Company c in companies) { ... }
}

It's a simple enough requirement - so how do we match that up on an HTML form?

<input name="company[MSFT].CompanyName" type="text" value="Microsoft" />
<input checked="checked" name="company[MSFT].Active" type="checkbox" value="true" />
<input name="company[AAPL].CompanyName" type="text" value="Plaaple" />
<input name="company[AAPL].Active" type="checkbox" value="false" />

As you can see, the key for the dictionary entry is used in the markup, this might not be available in run-time, so then we'd just use a standard List<company>, but this pattern is incredibly useful for updating existing records.

Breaking from the voyeuristic norms of the Internet, any comments can be made in private by contacting me.