All,
I’m new to MVC and therefore learning it as I go along by working on a new project. I have some simple functionality I would like to achieve but don’t know if I’m doing it the correct way – the current approach results in a runtime error – a description of the problem is below.
I’m trying to create some password reset functionality. To reset a password, I’m going to get the user to enter their username and e-mail on one view. Then on a second view I’m going to display their password reset question and get them to enter their password reset answer. The second view will also display their username, so I need to pass the entered username from view one into view two. I have the following two models so far:
public class ResetPasswordModelStepOne
{
[Required]
[Display(Name = "Username")]
public string Username { get; set; }
[Required]
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
}
public class ResetPasswordModelStepTwo
{
public ResetPasswordModelStepOne StepOneModel { get; set; }
[Display(Name = "Question")]
public string ResetQuestion { get; set; }
[Required]
[Display(Name = "Answer")]
public string ResetAnswer { get; set; }
}
Notice that the second model also has a property to store the step one model, this is so that on the second view, I can access and display the users username in a message like “Hi {Username}, to reset your password, please answer your password reset question.”. I have created strongly typed views for both the above models and have the following actions.
public ActionResult PasswordResetStepOne()
{
return View();
}
[HttpPost]
public ActionResult PasswordResetStepOne(ResetPasswordModelStepOne stepOneModel)
{
//Imagine i'm validating that the user exists here and then retrieving
//their secret question from a repository
var userSecretQuestion = "What is your favourite color?";
return PasswordResetStepTwo(new ResetPasswordModelStepTwo { StepOneModel = stepOneModel, ResetQuestion = userSecretQuestion });
}
public ActionResult PasswordResetStepTwo(ResetPasswordModelStepTwo stepTwoModel)
{
return View(stepTwoModel);
}
The problem I’m having with this approach is that when the user enters their username and email on the first step view, I then call the “PasswordResetStepTwo” action which returns the strongly typed view for ResetPasswordModelStepTwo – this results in the following runtime error:
The model item passed into the dictionary is of type
‘MvcCrossPageModel.Models.ResetPasswordModelStepTwo’, but this
dictionary requires a model item of type
‘MvcCrossPageModel.Models.ResetPasswordModelStepOne’.
Can someone explain what I’m doing wrong here? Is there a better way to achieve this in one view with one model? Am I doing this correctly by creating “step one” and “step two” models? Ideally I’d like to have a single view, the user enters their username and email – then the same view is returned prompting them for their secret question/
1 Answer