ModelState.IsValid does not exclude required property

后端 未结 7 1292
猫巷女王i
猫巷女王i 2020-12-06 12:22

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.

<
7条回答
  •  温柔的废话
    2020-12-06 12:46

    I am currently experiencing a similar issue with MVC3.

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

    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.

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

    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);
    

    The issue thus appears as if ModelState is still validating properties that have been excluded from your FormCollection.

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

    ModelState.Remove("Password");
    

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

提交回复
热议问题