I'm working on an MVC4 with EF6 project, and have run into a slightly small but frustrating problem. I have a situation where I have the [Required]
attribute set in my dbcontext, however, I do want to allow said property to be okay with empty strings.
I have tried what was suggested in this article, http://www.dzone.com/articles/ef-code-firstmvc, as well as putting [DisplayFormat(ConvertEmptyStringToNull = false)]
on my context properties.
When I POST from my login page, the First Name, Last Name, Email, Phone properties are null, which is throwing the ModelState
out of whack, even though I've set it to allow those properties to be empty strings. Am I missing something?
Model / DBContext
public class User : Entity
{
[StringLength(200)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
[Required]
public String UserName { get; set; }
[StringLength(250)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
[Required]
public String Password { get; set; }
[StringLength(200)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
[Required]
public String FirstName { get; set; }
[StringLength(200)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
[Required]
public String LastName { get; set; }
[StringLength(200)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
[Required]
public String Email { get; set; }
[StringLength(200)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
[Required]
public String Phone { get; set; }
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserViewModel Model)
{
var _UM = Model.User;
var User = _repo.GetSingle<User>(x => x.UserName == _UM.UserName);
if(User != null)
{
if (Hash.ValidatePassword(_UM.Password, User.Password))
{
return RedirectToAction("Dashboard");
}
else
{
ModelState.AddModelError("InvalidPass", "Invalid Credentials");
}
}
else
{
ModelState.AddModelError("NoUser", "Invalid Credentials");
}
return View(Model);
}
If invalid credentials are set, I would expect the ModelState
keys to only have one of the items that I am explicity setting. However, it has 6 keys (First Name, Last Name, etc are required).