1

你能帮我在 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>
}

那么,如果两个密码相同,我如何在我的控制器中验证?提前致谢

4

2 回答 2

5

另外,您可以在比较属性中添加两个密码不同时显示的消息。

[Compare("NewPassword", ErrorMessage = "The new password and confirm password do not match.")] 
于 2012-07-10T20:16:08.080 回答
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);
}
于 2012-04-23T08:00:51.063 回答