【问题标题】:Validating form using ModelState使用 ModelState 验证表单
【发布时间】:2010-10-27 15:06:09
【问题描述】:

我正在尝试使用 ModelState 验证表单,通常与 asp.net/mvc 上的教程相同。但是我没有自己的数据库或它们的对象,并且想针对 Formcollection 进行验证。我不确定 ModelState 是如何工作的,所以也许我是在黑暗中拍摄,但这是崩溃的代码:

我在 TextBox 上得到 NullReferenceException:

System.NullReferenceException:对象引用未设置为对象的实例。在 System.Web.Mvc.HtmlHelper.GetModelStateValue(String key, Type destinationType) 在 System.Web.Mvc.Html.InputExtensions.InputHelper(HtmlHelper htmlHelper, InputType inputType, String name, Object value, Boolean useViewData, Boolean isChecked, Boolean setId , Boolean isExplicitValue, IDictionary2 htmlAttributes) at System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper, String name, Object value, IDictionary2 htmlAttributes) at System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper, String name, Object value) at ASP.views_authorized_account_aspx.__RenderContent1(HtmlTextWriter __w, Control parameterContainer) in c:\ Users\Trimack\Documents\Visual Studio 2008\Projects\GuestManager\AccountManager\Views\Authorized\Account.aspx:第 61 行*

有什么想法吗?还是我完全错了?

特里马克

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    因此,对于您使用 ModelState.AddModelError() 添加的每个错误并再次调用 View,MVC 框架将尝试为它找到的每个错误查找一个 AttemptedValue。因为你没有添加它们,所以 MVC 会抛出异常。

    http://forums.asp.net/p/1396019/3006051.aspx

    如果有错误那么你还必须设置模型值以及模态错误

    ModelState.AddModelError("Some_Key","显示一些错误信息"); ModelState.SetModelValue("Some_Key", ValueProvider["Some_Key"]);

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 2021-02-09
    相关资源
    最近更新 更多