ASP.NET MVC Problem with validation

asp.net-mvc

I have this simple controller:

public class OneController : Controller
{
    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Create()
    {
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(IList<TestModel> m)
    {
        return View(m);
    }
}

And a very simple view with two objects of type TestModel, properly indexed.
When I submit the form with invalid data, I get the view with the errors highlighted.
However, when I re-submit it (without changing anything), I get this error:

[NullReferenceException: Object reference not set to an instance of an
object.]
System.Web.Mvc.DefaultModelBinder.UpdateCollection(ModelBindingContext
bindingContext, Type itemType) +612
System.Web.Mvc.DefaultModelBinder.BindModelCore(ModelBindingContext
bindingContext) +519
System.Web.Mvc.DefaultModelBinder.BindModel(ModelBindingContext
bindingContext) +829
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ParameterInfo
parameterInfo) +313
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(MethodInfo
methodInfo) +399
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName)
+232
System.Web.Mvc.Controller.ExecuteCore()
+152
System.Web.Mvc.ControllerBase.Execute(RequestContext
requestContext) +86
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext
requestContext) +28
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase
httpContext) +332
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext
httpContext) +55
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext
httpContext) +28
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+358
System.Web.HttpApplication.ExecuteStep(IExecutionStep
step, Boolean& completedSynchronously)
+64

Any idea on how can I debug this?

Best Answer

I was already looking at that article, and found the bug I was having (subtle, yet critical). If you render the hidden field with the index using Html.Hidden, the helper will "accumulate" the previous values, so you'll end up with a hidden saying index=1, and the next saying index=1,2.

Changing the helper call to a manually coded hidden field fixed the issue.