【问题标题】:ASP.NET MVC Problem with validationASP.NET MVC 验证问题
【发布时间】:2008-11-06 16:18:09
【问题描述】:

我有这个简单的控制器:

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

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

还有一个非常简单的视图,其中包含两个 TestModel 类型的对象,正确索引。 当我提交包含无效数据的表单时,我会看到突出显示错误的视图。 但是,当我重新提交它(不做任何更改)时,我收到了这个错误:

[NullReferenceException: 对象引用未设置为 目的。] System.Web.Mvc.DefaultModelBinder.UpdateCollection(ModelBindingContext bindingContext,类型 itemType) +612 System.Web.Mvc.DefaultModelBinder.BindModelCore(ModelBindingContext 绑定上下文)+519 System.Web.Mvc.DefaultModelBinder.BindModel(ModelBindingContext 绑定上下文)+829 System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ParameterInfo 参数信息)+313 System.Web.Mvc.ControllerActionInvoker.GetParameterValues(MethodInfo 方法信息)+399 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext 控制器上下文,字符串动作名称) +232 System.Web.Mvc.Controller.ExecuteCore() +152 System.Web.Mvc.ControllerBase.Execute(RequestContext 请求上下文)+86 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(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

关于如何调试它的任何想法?

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    我已经在查看那篇文章,并发现了我遇到的错误(微妙,但很关键)。 如果您使用 Html.Hidden 使用索引渲染隐藏字段,帮助程序将“累积”之前的值,因此您最终会得到一个隐藏的语句 index=1,下一个语句 index=1,2。

    将帮助程序调用更改为手动编码的隐藏字段修复了该问题。

    【讨论】:

    • 很高兴知道,感谢您发布您的解决方案,我敢打赌它会帮助遇到同样问题的其他人。
    【解决方案2】:

    如果不查看更多代码以及您的表单是如何设置的,我不确定我是否可以回答。 但是,您可以查看有关 Model Binding To A ListPhil Haack's 博客条目。
    希望这会有所帮助。

    【讨论】:

      【解决方案3】:

      谢谢你修复它!

      我换了

      <%= Html.Hidden("submitFormFields.index", controlID) %>
      

      <input type="hidden" id="submitFormFields.index" name="submitFormFields.index" value="<%=controlID %>" />
      

      我们是否应该将此报告为错误 - 为 ASP.Net MVC RC1 修复它会很好

      【讨论】:

      • 嗯,在 MVC 4 中仍然是个问题
      猜你喜欢
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      • 2012-03-30
      • 2011-07-31
      相关资源
      最近更新 更多