你能帮我在MVC3中构建我的“ChangePassword”视图吗?
这是我试图做的事情:
ProfileTeacherController.cs
public ViewResult ChangePassword(int id)
{
var user = User.Identity.Name;
int inter = int.Parse(user);
var teachers = from t in db.Teachers
where t.AffiliationNumber == inter
select t;
Teacher teacher = new Teacher();
foreach (var teach in teachers)
{
teacher = teach;
}
return View(teacher);
}
[HttpPost]
public ActionResult ChangePassword(Teacher teacher)
{
if (ModelState.IsValid)
{
// How can I compare the two fields password in my view ?
db.Entry(teacher).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Edit", "ProfileTeacher", new { id = teacher.TennisClubID });
}
return View(teacher);
}
此处为ChangePassword(查看)
@model TennisOnline.Models.Teacher
@{
ViewBag.Title = "ChangePassword";
}
<h2>Changement du mot de passe</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend></legend>
<div class="editor-label">
@Html.Label("Enter the new password")
</div>
<div class="editor-field">
@Html.PasswordFor(model => model.Pin, new { value = Model.Pin })
</div>
<div class="editor-label">
@Html.Label("Confirm your password")
</div>
<div class="editor-field">
@Html.Password("ConfirmPassword")
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
那么,如何在我的控制器中验证这两个密码是否相同呢?提前致谢
答案 0 :(得分:5)
此外,当比较属性中的两个密码不相同时,您可以添加要留言的消息。
[Compare("NewPassword", ErrorMessage = "The new password and confirm password do not match.")]
答案 1 :(得分:3)
我建议使用视图模型:
public class TeacherViewModel
{
...
[Compare("ConfirmPassword")]
public string Password { get; set; }
public string ConfirmPassword { get; set; }
}
现在让您的视图采用视图模型以及Post操作。
除了你的GET操作中,你似乎已经编写了一些foreach
循环,我没有看到它的用法。你可以简化:
[Authorize]
public ViewResult ChangePassword(int id)
{
var user = User.Identity.Name;
int inter = int.Parse(user);
var teacher = db.Teachers.SingleOrDefault(t => t.AffiliationNumber == inter);
return View(teacher);
}