I have a web application in ASP.Net MVC 4.
I have a model called User with many properties like Name, Email, Password, BirthDate, Gender, etc.
public class UserModel
{
public string UsrId { get; set; }
[Required(ErrorMessage = "Please enter the user's name.")]
public string UsrName { get; set; }
[Required(ErrorMessage = "Please enter the email.")]
public string UsrEmail { get; set; }
[Required(ErrorMessage = "Please enter the password.")]
public string UsrPwd { get; set; }
[Required(ErrorMessage = "Please select the gender")]
public ParamData Gender { get; set; }
[Required(ErrorMessage = "Please select birthdate")]
public string UsrBirthDate { get; set; }
//.... other properties
}
I used ModelState validation in a Login Validation. For Login I used the properties Email and Password. Both properties had Annotations of type "Required" , to validate not to enter empty strings. I used a ViewModel "LoginViewModel" viewmodel which one its properties was "User" type. I called ModelState.IsValid and it worked ok.
public class LoginViewModel
{
public UserModel LoginDat { get; set; }
// other props of ViewModel ...
}
Now I am doing a Registration (1st step of registration) validation. For that I have a "Register1ViewModel" viewmodel, and again, one of its properties is of type User model. But for registration (first step) I only need the following 3 User's properties: Name, Gender, BirthDate. Those properties are too in User Model. I wrote Required annotations for these 3 properties.
public class RegiViewModel
{
public UserModel RegiDat { get; set; }
// other props of ViewModel ...
}
But when I call ModelState.IsValid it results false because it asks for Email and Password properties.
[HttPost]
public ActionResult RegisterStep1Post(RegiViewModel VM, string Answer)
{
if (ModelState.IsValid)
{
RegiViewModel VM2 = GetSomeStuff(VM);
return View("Step2Validation", VM2); // Ok go next step
}
else
{
return View("RegiStep1ViewPost", VM); // return to form
}
}
Is there any way of use only a defined subset of a model's properties when using ModelState.IsValid? I don't want to duplicate my User model.