开发者

Re-evaluate the ModelState.IsValid property

I am trying to validate a user changing their password. The PasswordChange Class which this actionresult takes has 4 properties. one of which is the databasePassword which im compared against a "CurrentPassword" property which ensures the user can only change their password if they know their current password (pretty standard proceedure on websites)

Problem I have is the database password is only set (as shown) inside the ActionResult but the ModelState seems to get called before this so it returns false on "IsValid" because it sees the database password as "NULL" even after the database password is set

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult ChangePassword(PasswordChange model)
    {
        var User = GetPlayer().User;
        model.databasePassword = User.Password; 

        if (ModelState.IsValid)
        {
            //update the users password
            User.Updated = SystemDate.Current();
            User.Password = model.new开发者_如何学GoPassword.ToLower();

            return Redirect("/Player");
        }
        else
        {
            return View(model);
        }
    }

How can I go about reevaluating it or getting it to evaluate when i want it to!


Check the error and clear it if your assignment fixed it. Simplified check:

model.databasePassword = User.Password;
if (ModelState["databasePassword"].Errors.Count == 1)
{
    ModelState["databasePassword"].Errors.Clear();
}


Create a PasswordChangeInput view model class and pass in what you need from the view, you can then have separate validation from your entity model. Then you can use something like automapper to map the input view model to the entity model after your satisfied the input data is valid.

To add: you could try and clear out the ModelState errors, set the databasePassword, and re validate. It's probably easier to figure out what is causing the default model binder to add an error for databasePassword and change it so it doesnt.


I know its an old post, but I found another solution which might help someone struggling with the same scenario.

Conditional Validation with Data Annotations in ASP.NET MVC

or by creating ModelState extension

ASP.NET MVC - Excluding Model Validation Rules

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜