Tuesday, May 14, 2013

MVC4 NULL Action Form Binding Parameter

Suppose that you are creating a new POST action like the following:
[Authorize(Roles="Admin")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(DailyTotal total)
It would be reasonable to expect that a form posting all the correct values to create a new fully hydrated DailyTotal object, but that would be incorrect; you get a total parameter set to "null". The fix is mind numbingly simple, the variable must be the entity name in all lowercase characters.

The below example given the same POSTed data will produce a fully hydrated object.
[Authorize(Roles="Admin")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(DailyTotal dailytotal)

No comments: