2012-04-23 59 views
1

你能幫助我建立在MVC3我「ChangePassword」觀?查看「ChangePassword」在MVC 3

這裏我試圖做:

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

所以,我怎麼能在我的控制器中驗證是否兩個pa sswords是一樣的,請嗎?在此先感謝

回答

3

我會建議一個視圖模型的使用:

public class TeacherViewModel 
{ 
    ... 

    [Compare("ConfirmPassword")] 
    public string Password { get; set; } 

    public string ConfirmPassword { get; set; } 
} 

現在有你的觀點採取視圖模型,也是你的帖子行動。

除了在你的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); 
} 
+0

謝謝它很好用!並且還要感謝關於「foreach循環」的提示 – Razor 2012-04-23 09:08:39

4

另外,你可以添加消息,當這兩個密碼在比較屬性中不相同時。

[Compare("NewPassword", ErrorMessage = "The new password and confirm password do not match.")]