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



我有一个基于数据库的模型,这里是

//------------------------------------------------------------------------------
// <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|42d|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>
}

iam使用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说的那样解决了现在是我的观点:

@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>
}

它将空值返回给控制器

由于您有一个用于登录的特殊类,因此必须将其添加到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)

相关内容

  • 没有找到相关文章

最新更新