ASP.Net MVC RC2 ValidationMessage和表单字段冲突? [英] ASP.Net MVC RC2 ValidationMessage and form field conflict?

查看:107
本文介绍了ASP.Net MVC RC2 ValidationMessage和表单字段冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有MVC RC2的问题在哪里验证失败,失败的领域会抛出视图时传回给用户一个NullReferenceException。

I am having problems with MVC RC2 where upon validation failure, the failed field will throw a NullReferenceException when the view is passed back to the user.

一个短期的解决办法发现:这是重命名Html.ValidationMessage比目标表单域不同。这个作品!

A short term solution was found: which was to rename the Html.ValidationMessage to be different than the Target Form Field. This works!

但现在的自动突出显示从输入字段断开。 (开箱水煤浆是改变目标字段的CSS类,这使得它杰出的事物)

BUT now the automatic highlighting is disconnected from the input field. (Out of the box behavour is to change the target field's CSS Class which makes it standout)

所以...

什么是我的code的实际问题?

为什么它不会让我ValidationMessage和表单域共享相同的名字?

运行以下code时,code抛出的NullReferenceException:

The code is throwing NullReferenceException when the following code is run:

查看code

<% using (Html.BeginForm()) { %>
   <fieldset>
     <h5>Terms and Conditions</h5>
     <p>
       <%= Html.CheckBox("Terms", false)%>
       <%= Html.ValidationMessage("Terms")%>
       I agree to the <a href="/signup/terms">Terms & Conditions.</a>
     </p>
   </fieldset>
   <input class="signup_button" type="submit" title="Sign Up" value="" />
<% } %>
<%= Html.ValidationSummary("Sign up wasn't successful.")%>

控制器code

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection form)
{
    bool Terms = form["Terms"].ToString() == "true,false" ? true : false;

    if (Terms)
    {
        return RedirectToAction("Success", "Signup");
    }
    else 
    {
        ModelState.AddModelError("Terms", "Please agree to the Terms");
        ModelState.AddModelError("_FORM", "Terms not checked");
    }
    return View();
}

我可以得到code工作,如果我忽略了以下内容:

I can get the code to work if I omit the following:

ModelState.AddModelError("Terms", "Please agree to the Terms");

但有了这个,复选框抛出空引用异常。

But with this, the checkbox throws the Null reference exception.

任何想法?

推荐答案

试试这个:

else 
{
    ModelState.AddModelError("Terms", "Please agree to the Terms");
    ModelState.SetModelValue("Terms", form.ToValueProvider()["Terms"]);
    ModelState.AddModelError("_FORM", "Terms not checked");
}

如果还是不行,那么请张贴异常的完整的堆栈。

If that doesn't work, then please post the full stack for the exception.

这篇关于ASP.Net MVC RC2 ValidationMessage和表单字段冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆