简体   繁体   中英

Problem while posting data to the database in ASP.NET Core, ModelState is invalid

This is how my .cs file looks and when I debugged the code, ModelState does have some value in it. But still the compiler goes into the the if statement. Not sure what's going wrong

public async Task<IActionResult> OnPostAsync()
{
    if (!ModelState.IsValid)
    {
        return Page();
        Console.WriteLine("There is some problem in the model coming in");
    }

    using (var db = _context)
    {
        db.UserData.Add(new UserDatum { 
            Username = Request.Form["username"],
            Password = Request.Form["password"],
            EmailId = Request.Form["email"] 
        });;
        await db.SaveChangesAsync();
    }

    return RedirectToPage("./Index");
}

HTML File

@page
@model IndianPoliticalData.Pages.UserCredentials.RegisterModel

<div>
    <form method="post">
        
        <label>Enter Username</label>
        <input type="text" name="username" placeholder="Email"/>

        <label>Enter Password</label>
        <input type="password" name="password" placeholder="Password" />
        
        <label>Enter EmailId</label>
        <input type="email" name="email" placeholder="Email"/>

        <button type="submit">Register</button>
    </form>
</div>

This is how my models look

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;

namespace IndianPoliticalData.Models
{
    public partial class UserDatum
    {
        public UserDatum()
        {
            Bookmarks = new HashSet<Bookmark>();
        }

        [Key]
        [Column("ID")]
        public Guid Id { get; set; }
        [Column("username")]
        [StringLength(50)]
        [Unicode(false)]
        public string Username { get; set; } = null!;
        [Column("password")]
        [StringLength(50)]
        [Unicode(false)]
        public string Password { get; set; } = null!;
        [Column("emailId")]
        [StringLength(50)]
        [Unicode(false)]
        public string EmailId { get; set; } = null!;
        [Column("idCreatedTime", TypeName = "datetime")]
        public DateTime? IdCreatedTime { get; set; }

        [InverseProperty("User")]
        public virtual ICollection<Bookmark> Bookmarks { get; set; }
    }
}

Image of the ModelState in debug mode 在此处输入图像描述

I read some documentation about ModelState.IsValid and it states that if the form data doesn't match the model then this returns as false. Id and datetime are set to not null and take a default value.

Change your code, model binding need name attribute as same as property.

 <input type="email" name="EmailId" placeholder="Email"/>

Result:

在此处输入图像描述

You could add these codes to see the details of your error and share with us

if (!ModelState.IsValid)
            {
                var errorlist = new List<string>();
                List<string> keys = ModelState.Keys.ToList();
                foreach (var key in keys)
                {
                    var errors = ModelState[key].Errors.ToList();
                    errors.ForEach(x => { errorlist.Add(x.ErrorMessage); });
                }
            }

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM