模型验证错误消息不起作用并返回空

时间:2021-06-01 14:11:44

标签: .net asp.net-mvc

我有基于数据库的模型,它在这里

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Freelance.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public partial class User
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public User()
        { 
            this.JobPosts = new HashSet<JobPost>();
            this.Proposals = new HashSet<Proposal>();
            this.Reviews = new HashSet<Review>();
            this.SavedJobs = new HashSet<SavedJob>();
        }

        public int Id { get; set; }

        [RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", ErrorMessage = "Email is not valid.")]
        [Required(ErrorMessage = "Please enter Email"), MaxLength(50)]
        public string Email { get; set; }


        [Display(Name = "User Name")]
        [Required(ErrorMessage = "Please enter User Name"), MaxLength(40)]
        public string UserName { get; set; }

  
        [Required(ErrorMessage = "Please enter Password"), MaxLength(50)]
        public string Password { get; set; }
        [Required(ErrorMessage = "Please enter First Name"), MaxLength(40)]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Required(ErrorMessage = "Please enter Last Name"), MaxLength(40)]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }
        [RegularExpression(@"\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$", ErrorMessage = "Phone Number is not valid.")]
        [Required, MaxLength(30)]
        [Display(Name = "Phone Number")]
        public string PhoneNumber { get; set; }
        public string Photo { get; set; }
        [Display(Name = "User Type")]
        public string UserType { get; set; }


        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<JobPost> JobPosts { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Proposal> Proposals { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Review> Reviews { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<SavedJob> SavedJobs { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<UserLogin> UserLogins { get; set; }
    }

    public partial class UserLogin
    {
       

        [RegularExpression(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$", ErrorMessage = "Email is not valid.")]
        [Required(ErrorMessage = "Please enter Email"), MaxLength(50)]
        public string Email { get; set; }

        [MinLength(8, ErrorMessage ="Password must be at least 8 length")]
        [Required(ErrorMessage = "Please enter Password"), MaxLength(50)]
        public string Password { get; set; }

     



    }

}

我进行了用户登录,所以我只能使用电子邮件和密码登录,因为我无法发送用户模型,因为我在类中进行了验证,所以我创建了 UserLogin 类 这是我的控制器

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login([Bind (Include ="Email,Password")]UserLogin user)
        {
            
                System.Diagnostics.Debug.WriteLine(user.Email);
                System.Diagnostics.Debug.WriteLine(user.Password);
            
            if (ModelState.IsValid)
            {
                System.Diagnostics.Debug.WriteLine("valid");
                var data = db.Users.Where(u => u.Email.ToLower() == user.Email.ToLower() && u.Password == user.Password);
                if (data.Count() == 1)
                {
                    System.Diagnostics.Debug.WriteLine(data.SingleOrDefault().UserType);
                    FormsAuthentication.SetAuthCookie(data.SingleOrDefault().UserName.ToString(), true);
                    return RedirectToAction("CurrentUser");
                }
            }
            ModelState.AddModelError("", "invalid Username or Password");
            return RedirectToAction("Index", "Freelancer");
        }

这是视图中的表单

@model Freelance.Models.ViewModels.HomeViewModel
@using (Html.BeginForm("Login", "User", FormMethod.Post))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                        <div class="mb-3">
                            <label for="LoginEmail" class="form-label">Email address</label>
                            @Html.EditorFor(u => u.user.Email, new { htmlAttributes = new { @class = "form-control", @id = "LoginEmail", @type = "Email", @required = "" } })
                            @Html.ValidationMessageFor(u => u.user.Email, "", new { @class = "text-danger" })

                        </div>
                        <div class="mb-3">
                            <label for="LoginPassword" class="form-label">Password</label>

                            @Html.EditorFor(u => u.user.Password, new { htmlAttributes = new { @class = "form-control", @id = "LoginPassword", @type = "Password", @required = "" } })
                            @Html.ValidationMessageFor(u => u.user.Password, "", new { @class = "text-danger" })
                        </div>
                        <div class="mb-3 form-check">
                            <input type="checkbox" onclick="ShowPassword()" class="form-check-input" id="ShowPasswordCheckBox">
                            <label class="form-check-label" for="ShowPasswordCheckBox">Show Password</label>
                        </div>
                        <div class="d-flex justify-content-center">
                            <button type="submit" class="btn btn-primary">Login</button>
                        </div>

                    }

我使用 HomeViewModel 所以我可以在同一页面中访问不同的模型

 public class HomeViewModel
    {
        public List<ViewModel> testModel { get; set; }
        public List<JobPost> posts { get; set; }
        public JobPost post { get; set; }
        public List<User> users { get; set; }

        public User user { get; set; }
        public SavedJob savedPost { get; set; }
        public List<SavedJob> savedPosts { get; set; }

    }

当我尝试提交表单时,即使我提交了它也不会显示错误消息的问题
[MinLength(8)] 但在登录方法中它确实说它不是有效模型

我的问题是为什么它没有在 html 表单中显示错误消息?

我确实像 Serge Said 那样解决了它 现在这是我的观点:

 @using (Html.BeginForm("Login", "User", FormMethod.Post))
                    {
                        @Html.AntiForgeryToken()
                        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                        <div class="mb-3">
                            <label for="LoginEmail" class="form-label">Email address</label>
                            @Html.EditorFor(u => u.userLogin.Email, new { htmlAttributes = new { @class = "form-control", @id = "LoginEmail", @type = "Email", @required = "" } })
                            @Html.ValidationMessageFor(u => u.userLogin.Email, "", new { @class = "text-danger" })

                        </div>
                        <div class="mb-3">
                            <label for="LoginPassword" class="form-label">Password</label>

                            @Html.EditorFor(u => u.userLogin.Password, new { htmlAttributes = new { @class = "form-control", @id = "LoginPassword", @type = "Password", @required = "" } })
                            @Html.ValidationMessageFor(u => u.userLogin.Password, "", new { @class = "text-danger" })
                        </div>
                        <div class="mb-3 form-check">
                            <input type="checkbox" onclick="ShowPassword()" class="form-check-input" id="ShowPasswordCheckBox">
                            <label class="form-check-label" for="ShowPasswordCheckBox">Show Password</label>
                        </div>
                        <div class="d-flex justify-content-center">
                            <button type="submit" class="btn btn-primary">Login</button>
                        </div>

                    }

它向控制器返回空值

1 个答案:

答案 0 :(得分:0)

由于您有一个特殊的登录类,因此您必须将其添加到您的 ViewModel

 public class HomeViewModel
    {
        .....

        public User user { get; set; }
       
        public UserLogin userLogin { get; set; }
       ````

    }

修复您的登录视图

<div class="mb-3">
  <label for="LoginPassword" class="form-label">Password</label>
 @Html.EditorFor(u => u.userLogin.Password, new { htmlAttributes = new { @class = "form-control", @id = "LoginPassword", @type = "Password", @required = "" } })
@Html.ValidationMessageFor(u => u.userLogin.Password, "", new { @class = "text-danger" })
</div>

还有行动

[HttpPost]
 [ValidateAntiForgeryToken]
 public ActionResult Login(HomeViewModel viewModel)

或者如果你只是在登录视图中使用 UserLogin 作为模型可能会更好

@model Freelance.Models.ViewModels.UserLogin
.....

  <div class="mb-3">
   <label for="LoginPassword" class="form-label">Password</label>
@Html.EditorFor(u => u.Password, new { htmlAttributes = new { @class = "form-control", @id = "LoginPassword", @type = "Password", @required = "" } })
 @Html.ValidationMessageFor(u => u.Password, "", new { @class = "text-danger" })
   </div>

你也必须改变动作

[HttpPost]
 [ValidateAntiForgeryToken]
 public ActionResult Login(UserLogin userLogin)
相关问题