我正在尝试使用asp.net mvc 4
& EF6
我在哪里密码&确认密码字段。如果两者相同,则数据将像往常一样保存在MSSQL数据库中。我正在使用Compare
DataAnnotation
来比较这两个字段&我在EF6
生成的模型类中添加了该代码。但由于某种原因,我的数据没有保存在db中。这是我的代码,
控制器
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UserReg(ClientReg regCl)
{
if (ModelState.IsValid)
{
db.ClientRegs.Add(regCl);
db.SaveChanges();
return View();
else
{
return RedirectToAction("Register");
}
}
模型
public partial class ClientReg
{
public int serial { get; set; }
public string username { get; set; }
public string password { get; set; }
[Compare("password")]
public string ComparePass { get; set; }
}
查看
@model MyProj.Models.ClientReg
@using (Html.BeginForm("UserReg", "Home"))
{
@Html.ValidationSummary(true)
@Html.AntiForgeryToken()
<div class="editor-label">
<strong>Username</strong>
</div>
<div class="editor-field">
@Html.TextBoxFor(a => a.username)
@Html.ValidationMessageFor(a => a.username)
</div>
<div class="editor-label">
<strong>Password</strong>
</div>
<div class="editor-field">
@Html.PasswordFor(a => a.password)
@Html.ValidationMessageFor(a => a.password)
</div>
<div class="editor-label">
<strong>Confirm Password</strong>
</div>
<div class="editor-field">
@Html.PasswordFor(a => a.ComparePass)
@Html.ValidationMessageFor(a => a.ComparePass)
</div>
<input type="submit" value="Sign Up" />
}
我在代码中找不到任何错误。我在这里做错了吗?如何使用DataAnnotation比较两个密码字段?急需这个帮助!感谢。
答案 0 :(得分:1)
您应该将数据访问类与视图模型分开。视图模型应包含DataAnnotations.Compare属性。
/* View model */
public partial class ClientRegModel
{
public int serial { get; set; }
public string username { get; set; }
public string password { get; set; }
[Compare("password")]
public string ComparePass { get; set; }
}
/* Your DbContext or data class */
public partial class ClientReg
{
public int serial { get; set; }
public string username { get; set; }
public string password { get; set; }
}
您还可以查看此帖子How to properly implement "Confirm Password" in ASP.NET MVC 3?