ModelState.IsValid一直返回为false



所以我有一个视图,其中成员输入与他们相关的PIN以登录

@model Models.Member
@{
Layout = "~/Views/Shared/_HomeLayout.cshtml";
}
<h1 style="margin-top: 0px;">Club Members Login Below!</h1> @*add this to the style for better ipad title -> "text-align: center;"*@
</br>
@using (Html.BeginForm("ClubHours", "Login", FormMethod.Post))
{
@Html.LabelFor(c => c.PIN)
@Html.TextBoxFor(c => c.PIN)<br />
@Html.ValidationMessageFor(c => c.PIN)<br />
<input type="submit" name="submit" value="ClockIn" />
<input type="submit" name="submit" value="ClockOut" />
}

它与这个动作结果相互作用:

[HttpPost]
public ActionResult ClubHours(string submit, Member member)//member clocking in
{
if (submit.Equals("ClockIn"))
{
if (!ModelState.IsValid) //validating events fields
{
return View("UserLogin");
}
else
{
var mem = _context.Members.SingleOrDefault(c => c.PIN == member.PIN);
var hours = new MemberClubHours();
hours.ClockIn = DateTime.Now;
mem.Hours.Add(hours);
_context.SaveChanges();
return View("ClockIn");
}
}
else if (submit.Equals("ClockOut"))
{
if (!ModelState.IsValid) //validating events fields
{
return View("UserLogin");
}
else
{
var mem = _context.Members.SingleOrDefault(c => c.PIN == member.PIN);
var hours = new MemberClubHours();
hours.ClockOut = DateTime.Now;
mem.Hours.Add(hours);
_context.SaveChanges();
return View("ClockOut");
}
}
else
{
return View("UserLogin","Login");
}
}

最后是会员级

public class Member
{
public int Id { get; set; }
[Required]
[MaxLength(4, ErrorMessage = "PIN must be 4 numbers long"), MinLength(4, ErrorMessage = "PIN must be 4 numbers long")]
public string PIN { get; set; }
[Required]
[Display(Name ="First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Date of Birth")]
public DateTime? Birthdate { get; set; }
public virtual ICollection<MemberClubHours> Hours { get; } = new HashSet<MemberClubHours>();
}

和会员俱乐部小时类

public class MemberClubHours
{
public int Id { get; set; }
public DateTime? ClockIn { get; set; }
public DateTime? ClockOut { get; set; }
[Required]
public Member Member { get; set; }
}

该代码工作正常,将跟踪成员的工作时间,但我正在尝试实现验证,但即使我在系统中输入了与成员关联的PIN,它也会返回为无效?任何帮助都将不胜感激!

您正在验证从前端发送的模型。不是数据库,你确定模型是根据你在模型中的数据注释填充的吗?

查看ModelState,它是asp.net内核3.1,但仍然与相关

成员模型显示为无效,因为成员模型需要Id、PIN、FirstName和LastName字段。

您无法使用ModelState.IsValid验证此类,因为它将检查所有属性——并且看起来您只是在传递PIN属性

如果你不想为它创建一个viewModel,你可以将这些属性作为隐藏的输入字段;

@using (Html.BeginForm("ClubHours", "Login", FormMethod.Post))
{
@Html.HiddenFor(c=>c.Id)
@Html.HiddenFor(c=>c.FirstName)
@Html.HiddenFor(c=>c.LastName)
@Html.LabelFor(c => c.PIN)
@Html.TextBoxFor(c => c.PIN)<br />
@Html.ValidationMessageFor(c => c.PIN)<br />
<input type="submit" name="submit" value="ClockIn" />
<input type="submit" name="submit" value="ClockOut" />
}

相关内容

  • 没有找到相关文章

最新更新