Home > Enterprise >  ModelState.IsValid returns False even if the required property is valid
ModelState.IsValid returns False even if the required property is valid

Time:06-19

ModelState.IsValid returns false even if the properties with Required annotation have valid values. I logged the string representation of the object and it shows that the Username and Password is not empty.

User Model

public class User
{
    public int Id { get; set; }

    [Required]
    public string Username { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    public override string ToString()
    {
         return $"Username: {Username}, Password: {Password}";
    }


}

Controller

public class AuthController : Controller
{
    private readonly UserContext _context;
    private readonly ILogger<User> _logger;
    [BindProperty]
    public User AuthUser { get; set; }

    public AuthController(ILogger<User> logger, UserContext context)
    {
        _logger = logger;
        _context = context;
    }
    public IActionResult Login()
    {
        return View(new User());
    }
    [HttpPost]
    public async Task<IActionResult> Login(string returnURL = null)
    {
        if (!ModelState.IsValid) 
        {
             _logger.LogInformation(AuthUser.ToString());
             //Executes this block even if Username and Password has data
        }


    }

CodePudding user response:

    public IActionResult Login()
    {
        return View(new User());
    }

    [HttpPost]
    public async Task<IActionResult> Login(User model,string returnURL = null)
    {
        if (ModelState.IsValid) 
        {
             _logger.LogInformation(model.ToString());
        }
        return View(model);
    }
  • Related