ModelState.IsValid不排除必需的属性

lar*_*ole 8 asp.net-mvc

我试图排除一个必需的属性(密码),因此模型状态不会验证该属性,但由于某种原因,即使我尝试排除它,它仍然会验证.

控制器:

    [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);
    }
Run Code Online (Sandbox Code Playgroud)

视图:

   ...
   <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>
Run Code Online (Sandbox Code Playgroud)

用户(使用dataannotation):

[Required]
public string Password { get; set; }
Run Code Online (Sandbox Code Playgroud)

我使用的是VS2008,MVC2,firefox

也许我只是累了,看不到它.任何帮助表示赞赏

Mar*_*tor 16

我目前遇到与MVC3类似的问题.

尽管[Bind(Exclude = "Password")]在我的行动中,ModelState.IsValid仍然返回false.

我注意到这TryUpdateModel(user, null, null, new string[]{"Password"});是成功更新模型; 但仍然返回假.然后我发现(在stackoverflow上的某个地方,道歉没有链接)TryUpdateModel实际返回ModelState.IsValid.

因此,问题不在于TryUpdateModel,而在于ModelState.IsValid.

注意:这也意味着您不需要两次验证...您可以使用此代码:

if (!TryUpdateModel(user, null, null, new string[]{"Password"}))
    return PartialView(user);
Run Code Online (Sandbox Code Playgroud)

因此,问题似乎是ModelState仍在验证已从您的网站中排除的属性FormCollection.

我能够通过ModelState在调用之前删除字段来克服这个问题TryUpdateModel:

ModelState.Remove("Password");
Run Code Online (Sandbox Code Playgroud)

请注意,TryUpdateModel仍然需要根据上述代码从更新中排除属性列表.