Since I upgraded from MVC 2 to MVC 3 RC, using TryUpdateModel causes a NullReferenceException. This problem only occurs when running my action method as part of a unit test. Running it on the actual server works as expected.
Here’s a stack trace of the exception:
System.NullReferenceException: Object
reference not set to an instance of an
object. at
System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext
controllerContext) at
System.Web.Mvc.ValueProviderFactoryCollection.<>c_DisplayClassc.b_7(ValueProviderFactory
factory) at
System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()2.MoveNext()
at
System.Linq.Enumerable.WhereSelectEnumerableIterator
at
System.Collections.Generic.List1..ctor(IEnumerable1
collection) at
System.Linq.Enumerable.ToList[TSource](IEnumerable`1
source) at
System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext
controllerContext) at
System.Web.Mvc.Controller.TryUpdateModel[TModel](TModel
model, String prefix)
… my own code from here on….
In case it matters, my controller has the following signature:
[AcceptVerbs(HttpVerbs.Post)]
public virtual ActionResult Edit(int id, FormCollection collection)
{
}
My guess is that this has to do with the new way DI works in MVC3, but I can’t figure out what I’m doing wrong. Perhaps there is something in terms of DI setup that is required in MVC 3, but wasn’t required in MVC 2?
In case someone else has the same problem and finds this post:
I solved the problem generically based on Ivan Kortym’s answer (thanks!), with the following piece of code in my controller base class constructor: