In an mvc3 project I want to have 2 forms on one page. One form is to register a user and the other one is to logon.
There are two submit buttons. One to register, one to logon.
In the model there are validation annotiation e.g. username is required, passwords must match and so on.
The problem is, that the validation annotiation affect each other. So that when the register button is pressed, the validation for the logon username is invalid.
I have tried to write partial views, or to do everything in one view an write some custom annotiations, respecting the pressed button.
But that all seems to wrong. That can not be the best solution.
What would be the best way to achieve this.
The way I approach this problem; where you need 2 or more ViewModels binding to your view, is to create a encompasing ViewModel with 2 properties, then assign the individual login and register models to each property. e.g. (minus any validation you wish to add)
public class LogOnViewModel {
public string UserName { get; set; }
public string Password { get; set; }
}
public class RegisterViewModel {
public string UserName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
}
public class WelcomeScreenViewModel {
public LogOnViewModel LogOnModel { get; set; }
public RegisterViewModel RegisterModel { get; set; }
}
In my Welcome view I would have @model namespace.WelcomeScreenViewModel
at the top together with 2 partial views pointing to _LogOn and _Register like this:
@Html.Partial("_LogOn", Model.LogOnModel)
@Html.Partial("_Register", Model.RegisterModel)
That way your partial views are passed the correct models and are also re-usable as partial view else where in your web app.