When using strongly typed views, don’t name the controller action arguments with the same name as another form value!
I’ve been working with ASP.NET MVC for a couple of months now. It is really pretty awesome. It’s worked so well, I haven’t had much to blog about! The other day I ran into an issue so I’m sharing the solution. MVC will “automagically” bind the parameters of a controller action based on the values in the form. And if your View is strongly typed and your controller action has a parameter of that same type, it will bind it too. But in my case, the parameter was null. MVC wasn’t loading it. And there was no exception to help me out.
Here’s a simple demo, I’m not showing every line of code…
Typical for an MVC application, I have a view that is strongly typed:
<%@ Page Title=”” Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master”
The View has a simple form which includes two text boxes:
<%= Html.TextBox(“OrganizationName”) %>
<%= Html.ValidationMessage(“OrganizationName”, “*”) %>
<%= Html.TextBox(“Role”) %>
<%= Html.ValidationMessage(“Role”, “*”) %>
A button on the form posts back to the controller, calling the Create Action. Here is Action Code:
public ActionResult Create(OrganizationRole role)
// Do Something Here…
In the screenshot below, you can see that when I debug the app, the role parameter has not been loaded.
The fix was simple but it took a while to figure it out! All I had to do was re-name the parameter from “role” to “organizationRole”:
public ActionResult Create(OrganizationRole organizationRole)
// Do Something Here…
You see, I was being lazy and abbreviated the argument’s name. That is ok, you can name the parameter almost anything you want. But I gave the parameter the same name as one of the other form variables! Notice above that my form has a text box named “Role”! MVC tried to load the values of my parameters – it takes each of the posted values from the form (“OrganizationName” and “Role”) and tries to match them up with arguments with the same names (it is not case sensitive) if they exist. It also tries to load the entire form value (strongly typed as the class OrganizationRole) to the argument of type OrganizationRole, if one exists. But an argument of type OrganizationRole with the name “Role” screws the who thing up! The only problem is that it doesn’t throw any exceptions. Anyway, I changed the name and presto, it works.