At least once a week, a user will ask a question on one of the asp.net-mvc sites as to why their model, or a property of their model is null
when they submit their form back to the controller's action method.
The majority of these questions are also tagged c# and often these questions are closed as a duplicate of (the excellent) What is a NullReferenceException and how do I fix it?, usually by a well meaning c# gold badge owner who is, I assume, not familiar with MVC, and in particular the model binding process.
There are at least half a dozen reasons why the model could be null
, including this one I answered yesterday. Others include using foreach
loops instead of for
loops to generate collections in the view, using fields instead of properties in the model, including hidden inputs for properties which are complex objects, etc. Unless the OP was to download and step through the source code to understand how the DefaultModelBinder
code matches up a form's name/value pairs to model properties, the answers in the duplicate above are not going to help solve the problem.
Prior to my earning a gold badge in asp.net-mvc, all I could do was leave a comment and a link to another answer which did explain and solve the problem. Now that I have it, I've been re-opening the questions, but as soon as I try to close it again as a duplicate of a question that does answer it, I'm told I have to wait a couple of weeks. In the meantime, the question gets closed again as a duplicate of What is a NullReferenceException and how do I fix it?, so I'm back to leaving a comment, which might help the OP, but perhaps not others, especially if its lost in a forest of other comments.
I had thought of editing the accepted top answer, but its already long enough, or adding my own answer to address specific asp.net-mvc issues but that will just rot at the bottom - I got a blister scrolling to the bottom of the page as it is :)
Are there any other options I have to ensure the duplicate is the correct one to answer the question.