I have one view and that view contains create user and login forms. For both i have different models. When user clicks on Register button i will pass register model values and for login click i pass login model values.I have added some validation in model also (You can see it my code below).
Since i have two model i have added one more model(Account) which holds both this model.Am pssing this model(Account) from view to controller on click of register or login.
The reason why Model is invalid all the time is, when user clicks on login button am passing account model which has both Register and login model but with only login details .All the values for register model will be null since user clicked on login (Only login data will be there).So in controller Model.Isvalid is always false since no values are there for register model.
So is there any other way to validate a particular model ?
What is the solution in this case?
@model Selfie.Models.Account
//Register
@using (Html.BeginForm())
{
@Html.TextBoxFor( model => model.RegisterModel.FirstName,null, new {@class="form-control",id="fn", placeholder=" First Name",required="true",maxlength="20"})
@Html.ValidationMessageFor(model => model.RegisterModel.FirstName)
@Html.TextBoxFor(model => model.RegisterModel.LastName,null, new { @class = "form-control",id="ln", placeholder=" Last Name",required="true",maxlength="20"})
@Html.ValidationMessageFor(model => model.RegisterModel.LastName)
<button type="submit" class="btn btn-success" id="btnsub">Create Account</button>
}
//Login
@using (Html.BeginForm("Login", "Selfie", FormMethod.Post, new { }))
{
@Html.TextBoxFor(model => model.LoginModel.UserName,null, new { @class = "form-control",id="lem"})
@Html.ValidationMessageFor(model => model.LoginModel.UserName)
@Html.TextBoxFor(model => model.LoginModel.Pwd,null, new { @class = "form-control"})
@Html.ValidationMessageFor(model => model.LoginModel.Pwd)
<button type="submit" class="btn btn-success" id="btnlogin">Log In</button>
}
Controler
[HttpPost]
public ActionResult Register(Account registration)
{
if(Model.Isvalid)
{
string a= Account.fname;
}
}
[HttpPost]
public ActionResult Login(Accountlogin)
{
if(Model.Isvalid)
{
string a= Account.username;
}
}
Model
public class RegistrationModel
{
[Required(ErrorMessage="First name is required")]
public string FirstName { get; set; }
[Required(ErrorMessage="Password is required")]
public string Pwd { get; set; }
}
public class LoginModel
{
[Required(ErrorMessage = "User name is required")]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required(ErrorMessage = "Password is required")]
public string Pwd { get; set; }
}
public class Account
{
public LoginModel LoginModel{get; set;}
public RegistrationModel RegisterModel {get; set;}
}