asp.net mvc的添加验证导致模型为null [英] asp.net mvc adding validation causes Model to be null

查看:249
本文介绍了asp.net mvc的添加验证导致模型为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是完成了我的第一个asp.net的MVC的网站,但我却高兴不起来与验证的稳健性。

i just about finished my first asp.net mvc site but i wasn't happy with the robustness of the validation.

我在验证读了,然后添加下面的code到我的编辑行动,我UsersController:

i read up on validation and then added the below code to my Edit action in my UsersController:

  if (user_.firstname.Trim().Length == 0)
        {
            ModelState.AddModelError("firstname", "First Name is required.");
            return View();
        }

我只是做了这个测试,我现在在我看来收到错误,其中型号为NULL。

i just did a test on this and i now am getting errors in my view where the Model is null.

<% using (Html.BeginForm())
   {%>
<fieldset>
    <legend>Fields</legend>
    <p>
        <label for="Email">
            Login Name:
            <%= Model.loginName%>
        </label>
    </p>
    <p>

所以在上面的型号为空,所以我得到Model.loginName异常。任何想法怎么回事就在这里。如果删除上述code(验证),一切工作正常。 (但我可以再放入垃圾在我的数据库。

So in the above Model is null so i get an exception on Model.loginName. any idea whats going on here. If i remove the above code (the validation) everything works fine. (except that i can then put garbage in my database.

推荐答案

请参阅我的一个类似的话题回应。

See my response on a similar topic.

<一个href=\"http://stackoverflow.com/questions/887757/validating-form-using-modelstate/888103#888103\">http://stackoverflow.com/questions/887757/validating-form-using-modelstate/888103#888103

每次添加一个模型误差的ModelState中并再次调用认为,asp.net MVC框架试图寻找未遂值。你还应该查看的用户_对象返回到你的强类型查看。

Every time you add a model error to the ModelState and call the View again, the asp.net MVC framework tries to look for the attempted value. Also your View should return the user_ object to your strongly typed View.

if (user_.firstname.Trim().Length == 0)
{
    ModelState.AddModelError("firstname", "First Name is required.");
    ModelState.SetModelValue("firstname", ValueProvider["firstname"]);

    return View(user_);
}

这篇关于asp.net mvc的添加验证导致模型为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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