ModelState.IsValid不排除必要的财产 [英] ModelState.IsValid does not exclude required property

查看:159
本文介绍了ModelState.IsValid不排除必要的财产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着去排除所需的属性(密码),这样的ModelState不验证属性,但由于某种原因,它仍然验证,即使当我尝试将它排除在外。

Im trying to exclude a required property(Password) so the modelstate dont validate that property, but for some reason it still validate even when i try to exclude it.

控制器:

    [Authorize, AcceptVerbs(HttpVerbs.Post)]
    public ActionResult _Edit(int id, [Bind(Exclude = "Password")]FormCollection collection)
    {
        var user = Proxy.GetUser(id);

        TryUpdateModel(user, null, null, new[]{"Password"});

        if(!ModelState.IsValid)
            return PartialView(user);

        Proxy.UpdateUser(user);
    }

查看:

   ...
   <tr>
       <td class="label">
           <label class="row_description" for="Password"><%= S._("Password")%></label>
       </td>
       <td>
           <%= Html.Password("Password", null, new { @class = "row_input" })%>
           <%= Html.ValidationMessage("Password", "*")%>
       </td>
   </tr>

用户(使用dataannotation):

User(using dataannotation):

[Required]
public string Password { get; set; }

使用VS​​2008

IM,MVC2,火狐

Im using VS2008, MVC2, firefox

也许我只是太累了,不能看到它。任何帮助AP preciated

Maybe im just tired and can't see it. Any help is appreciated

推荐答案

我目前遇到MVC3类似的问题。

I am currently experiencing a similar issue with MVC3.

尽管 [绑定(不包括=密码)] 在我的行动, ModelState.IsValid 仍返回false

Despite [Bind(Exclude = "Password")] in my Action, ModelState.IsValid still returns false.

我注意到 TryUpdateModel(用户,NULL,NULL,新的String [] {密码}); 已成功更新模型;但仍返回false。后来我发现(计算器上的某个地方,不具有链接的道歉)是 TryUpdateModel 实际上返回 ModelState.IsValid

I noticed that TryUpdateModel(user, null, null, new string[]{"Password"}); was successfully updating the model; however still returning false. I then found out (somewhere on stackoverflow, apologies for not having the link) that TryUpdateModel actually returns ModelState.IsValid.

因此​​,这个问题是不是与 TryUpdateModel ,但 ModelState.IsValid

Thus, the issue is not with TryUpdateModel, but with ModelState.IsValid.

注:这也意味着你不需要验证这两次......你可以使用这个code:

NB: this also means that you do not need to verify this twice... you can use this code:

if (!TryUpdateModel(user, null, null, new string[]{"Password"}))
    return PartialView(user);

因此​​出现问题,因为如果ModelState中仍确认已排除性的的FormCollection

我能够从的ModelState 调用之前 TryUpdateModel 删除字段来解决这个问题:

I was able to overcome this by removing the field from ModelState prior to calling TryUpdateModel:

ModelState.Remove("Password");

注意TryUpdateModel仍然需要属性的列表,从更新按照上述code排除。

Note that TryUpdateModel still requires the list of properties to exclude from the update as per the above code.

这篇关于ModelState.IsValid不排除必要的财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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