I am using VS2010 RC at the time of this post.
I ran into a small issue with model binding in ASP.NET MVC. In my controller I had written an Add method for a custom type (one of the types in my model). My view had a form on it with all the appropriate fields, named and ID’d correctly.
The problem was that my model values, after the method was invoked, was always null.
To fast-forward a bit here, the reason seems to be that my parameter name was the same as a property on the type, which confused the MVC binding for some reason. This post is an expanded example of how I got into the nullifying state.
A Simple Example
Basically, I had a simple object in my models that I wanted the user to be able to add. It only had a few properties. Here’s an example of what it might look like:
It’s fairly straightforward. My form looked similar to the following:
…with all the fields in the model accounted for. I have used this multiple times in the past and wasn’t expecting any kind of complication.
My controller action accepted the type as a parameter (in this case it would be RecipeIngredient) and tried to persist the object; however, the parameter was always Null.
Again, the ASP.NET MVC engine, though routing correctly, seemed to run into trouble when trying to bind the model. Though all form values were submitted (Request.Form[“RecipeId”] and others had values), the parameter was never populated with the form values.
Notice that the parameter is named “ingredient” and that Ingredient is a property in my RecipeIngredient class. This is what cause the problem.
Now, Watch This
The fix for this was too simple: just rename the parameter on the controller action.
All of a sudden, the model lights up.
It took me a good 30 minutes to figure this out, so I hope it helps someone. I had actually found a post where someone with a similar scenario believed it to be a problem with the using() syntax or the Ajax.BeginForm (which is what I was using), so I was chasing a red herring for a while.
So, for me more than anyone, just remember: your model will not be properly bound in ASP.NET MVC controller actions if your parameter name is also a property in your model. The correct action will be invoked, but you will always get Null.
Hi, thank you very much. I had the same problem.
ReplyDeleteThanks very much. I had this problem for days and would never have thought what you said was the cause
ReplyDeleteThanks Lifesaver.
ReplyDeleteThis one was a ball breaker!!! Many thanks :)
ReplyDeleteThanks. Helped me with similar problem. Really weird behavior.
ReplyDeleteSpot on!
ReplyDeletePhew - I thought I was losing my sanity. Thanks
ReplyDelete