views:

413

answers:

1

Hey everyone,

I am having some problems getting the MVC modelstate working with a login process on a website. I have a typical login screen with fields for a username and password. The Account Controller has 2 methods to handle logins. The first is a Get method called "LogOn()" that just returns the login view (which is the username/pw), and the second is also called "LogOn(FormCollection values)", but it has [AcceptVerbs(HttpVerbs.Post)] specified.

So if a user tries to login without putting in a username and/or pw, the post method checks for that, and adds errors to the ModelState via ModelState.AddModelEror(). That is the first thing that happens, and after that has been validated, if the ModelState.IsValidated() is false, then I just return View().

//(validate just adds to Modelstate when values are null)
if (!ValidateLogOn(userName, password)) 
   return View();

Now, this works great, if either are blank then the page just returns and displays the correct error message using HtmlValidationMessage(keyName). The problem is that after that is validated, I then make the actual login call to start the authentication process for the supplied username/pw, which is wrapped in a try/catch block. If an error occurs in this process, I would like to add the error to the ModelState, and return the View(), just like I did above. The error is successfully being added to the ModelState, and the View is running through the code correctly, but after that happens, somehow the Get Logon() method is being called, which then overwrites everything and just display the View as if it was the users first time visiting the page!

So the overall code process is similar to that posted below:

public ActionResult LogOn()
{
   return View();
}

public ActionResult LogOn(FormCollection values)
{
    if (!ValidateLogOn(userName, password))
       return View();

    try {
        loginProcess(username, password);
    }
    catch (Exception e) {
        ModelState.AddModelError(keyName, "Error Message");
        return View();
    }

   return View();
} 

Any help or insight into why this process is working the way it does would be greatly appreciated, thanks!!

A: 

You need to explicitly set the value. Example for username:

ModelState.SetModelValue(
    "username", 
    new ValueProviderResult(username, username, CultureInfo.InvariantCulture));
Darin Dimitrov
Hey Darin, thanks for the response.I tried adding the above line by itself, and I also tried it with the AddModelError() happening first. Because if you just try SetModelValue() then the ModelState.IsValid does not get set to false. However, this did not correct the problem, and the overwriting Get call is still happening.Any other ideas??
Trevor