Adr*_*ore 8 asp.net-mvc dependency-injection model-binding asp.net-mvc-3
自从我从MVC 2升级到MVC 3 RC后,使用TryUpdateModel会导致NullReferenceException.仅当将我的操作方法作为单元测试的一部分运行时,才会出现此问题.在实际服务器上运行它按预期工作.
这是异常的堆栈跟踪:
System.NullReferenceException:未将对象引用设置为对象的实例.在System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext)的System.Web.Mvc.ValueProviderFactoryCollection.<> c_ DisplayClassc.b _7(ValueProviderFactory factory)处于System.Linq.Enumerable.WhereSelectEnumerableIterator
2.MoveNext() at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()处于System.1..ctor(IEnumerableSystem.Web.Mvc.Controller.TryUpdateModel中System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext)的System.Linq.Enumerable.ToList [TSource](IEnumerable`1 source)上的Collections.Generic.List 1 collection)[ TModel](TModel模型,字符串前缀)
......我自己的代码来自这里......
如果重要,我的控制器有以下签名:
[AcceptVerbs(HttpVerbs.Post)]
public virtual ActionResult Edit(int id, FormCollection collection)
{
}
Run Code Online (Sandbox Code Playgroud)
我的猜测是,这与DI在MVC3中工作的新方式有关,但我无法弄清楚我做错了什么.也许在MVC 3中需要一些DI设置,但在MVC 2中不需要?
Iva*_*tin 15
你应该添加这个代码:
FormCollection formValues = new FormCollection()
{
{ "Test", "test" },
{ "FirstName", "TestName" }
};
rootController.ValueProvider = formValues.ToValueProvider();
Run Code Online (Sandbox Code Playgroud)
我有同样的问题,这段代码对我有帮助.
如果其他人遇到同样的问题并找到这篇文章:
我一般根据 Ivan Kortym 的答案解决了这个问题(谢谢!),在我的控制器基类构造函数中使用以下代码:
if (Request!=null && Request.Form != null && Request.Form.HasKeys() && ValueProvider == null)
{
ValueProvider = new FormCollection(Request.Form).ToValueProvider();
}
Run Code Online (Sandbox Code Playgroud)