I need some help with this one….
I have this simple model:
public class Candidat
{
public string LoginEmail { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Prénom")]
public string FirstName { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Nom")]
public string LastName { get; set; }
}
I also have a controller like this:
[Authorize]
public ActionResult Index(Candidat model)
{
if (model.LoginEmail == null)
{
model = null;
using (var db = new rhDB())
{
MembershipUser user = Membership.GetUser();
if (user != null)
{
model = (from m in db.Candidates where m.LoginEmail == user.Email select m).SingleOrDefault();
}
if (model == null)
{
model = new Candidat();
model.LoginEmail = user.Email;
model.Email = user.Email;
}
}
}
return View("MyProfileCandidate", model);
}
As you can see, I check if the user as an existing record in the database. If not, I create a new instance of the model and set some default values… Then, I pass it to an EditView.
The problem is that my view show with the error validation messages… For all required fields…
Of course, this is because those fields are empty and required… It seems like the view think I am posting back an invalid model… Is there a way to hide those validation message ?
Try clearing the model state if you intend to modify some of the values on your model in the POST action:
The reason for this is that HTML helpers will use model state values that were initially posted instead of those in the model. You could also clear individual fields in the model state:
ModelState.Remove("FirstName");.