程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> MVC4制作網站教程第二章 用戶密碼修改2.3

MVC4制作網站教程第二章 用戶密碼修改2.3

編輯:ASP.NET基礎

一用戶
1.1用戶注冊 
1.2用戶登錄 
1.3修改密碼 

修改密碼會用到一個UserChangePassword 模型類,先添加UserChangePassword類 

/// <summary>
  /// 用戶修改密碼模型
  /// </summary>
  [NotMapped]
  public class UserChangePassword
  {
    /// <summary>
    /// 原密碼
    /// </summary>
    [Display(Name = "原密碼")]
    [Required(ErrorMessage = "×")]
    [StringLength(20, MinimumLength = 6, ErrorMessage = "×")]
    [DataType(DataType.Password)]
    public string Password { get; set; }
    /// <summary>
    /// 新密碼
    /// </summary>
    [Display(Name = "新密碼", Description = "6-20個字符。")]
    [Required(ErrorMessage = "×")]
    [StringLength(20, MinimumLength = 6, ErrorMessage = "×")]
    [DataType(DataType.Password)]
    public string NewPassword { get; set; }
    /// <summary>
    /// 確認密碼
    /// </summary>
    [Display(Name = "確認密碼", Description = "再次輸入密碼。")]
    [Compare("NewPassword", ErrorMessage = "×")]
    [DataType(DataType.Password)]
    public string ConfirmPassword { get; set; }
  }

用到了數據庫的更新,先打開UserRepository.cs 修改Update函數

/// <summary>
    /// 更新用戶信息
    /// </summary>
    /// <param name="user"></param>
    /// <returns></returns>
    public override bool Update(User user)
    {
      dbContext.Users.Attach(user);
      dbContext.Entry<User>(user).State = System.Data.EntityState.Modified;
      if (dbContext.SaveChanges() > 0) return true;
      else return false;
    }

在修改密碼時需要查出用戶信息並更新,需要添加Find(string UserName) 函數 

/// <summary>
    /// 查找用戶
    /// </summary>
    /// <param name="UserName">用戶名</param>
    /// <returns></returns>
    public User Find(string UserName)
    {
      return dbContext.Users.SingleOrDefault(u => u.UserName == UserName);
    }

好了打開UserController,添加ChangePassword Action 

/// <summary>
    /// 修改密碼
    /// </summary>
    /// <returns></returns>
    [UserAuthorize]
    public ActionResult ChangePassword()
    {
      return View();
    }
    [HttpPost]
    [UserAuthorize]
    public ActionResult ChangePassword()
    {
      return View();
    }

添加強類型(UserChangePassword)視圖,在視圖中添加三個文本框,修改後的視圖代碼 

@model Ninesky.Models.UserChangePassword
@{ 
  ViewBag.Title = "修改密碼";
  Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="banner">
  <img src="~/Skins/Default/Images/banner.jpg" />
</div>

@using (Html.BeginForm())
{
  @Html.ValidationSummary(true)

  <div class="form">
    <dl>
      <dt>修改密碼</dt>
      <dd>
        <div class="label">@Html.LabelFor(model => model.Password):</div>
        <div class="ctrl">@Html.PasswordFor(model => model.Password)
          @Html.ValidationMessageFor(model => model.Password)
          @Html.DisplayDescriptionFor(model => model.Password)
        </div>
      </dd>
      <dd>
        <div class="label">@Html.LabelFor(model => model.NewPassword):</div>
        <div class="ctrl">@Html.PasswordFor(model => model.NewPassword)
          @Html.ValidationMessageFor(model => model.NewPassword)
          @Html.DisplayDescriptionFor(model => model.NewPassword)
        </div>
      </dd>
      <dd>
        <div class="label">@Html.LabelFor(model => model.ConfirmPassword):</div>
        <div class="ctrl">@Html.PasswordFor(model => model.ConfirmPassword)
          @Html.ValidationMessageFor(model => model.ConfirmPassword)
          @Html.DisplayDescriptionFor(model => model.ConfirmPassword)
        </div>
      </dd>
      <dd>
        <div class="label"></div>
        <div class="ctrl">
          <input type="submit" value="修改密碼" />@Html.ValidationMessage("Message")
        </div>
      </dd>
    </dl>
    <div class="clear"></div>
  </div>
}
@section Scripts {
  @Scripts.Render("~/bundles/jqueryval")
}

修改UserController中[HttpPost]方式的ChangePassword()以實現修改密碼,修改完成的代碼如下: 

[HttpPost]
    [UserAuthorize]
    public ActionResult ChangePassword(UserChangePassword userChangePassword)
    {
      userRsy = new UserRepository();
      if (userRsy.Authentication(UserName, Common.Text.Sha256(userChangePassword.Password)) == 0)
      {
        var _user = userRsy.Find(UserName);
        if (_user == null)
        {
          Error _e = new Error { Title = "修改密碼失敗", Details = "修改密碼時,系統查詢不到用戶信息", Cause = Server.UrlEncode("<li>用戶在修改密碼界面停留的時間過長,登錄信息已失效。</li><li>系統錯誤。</li>"), Solution = Server.UrlEncode("<li>返回<a href='" + Url.Action("ChangePassword", "User") + "'>修改密碼</a>頁面,輸入正確的信息後重新注冊</li><li>聯系網站管理員</li>") };

          return RedirectToAction("Error", "Prompt", _e);
        }
        _user.Password = Common.Text.Sha256(userChangePassword.NewPassword);
        if (userRsy.Update(_user))
        {
          Notice _n = new Notice { Title = "成功修改密碼", Details = "您已經成功修改密碼,請牢記您的新密碼!", DwellTime = 5, NavigationName = "登陸頁面", NavigationUrl = Url.Action("Login", "User") };
          return RedirectToAction("Notice", "Prompt", _n);
        }
        else
        {
          Error _e = new Error { Title = "修改密碼失敗", Details = "修改密碼時,更新數據庫失敗!", Cause = Server.UrlEncode("<li>系統錯誤。</li>"), Solution = Server.UrlEncode("<li>返回<a href='" + Url.Action("ChangePassword", "User") + "'>修改密碼</a>頁面,輸入正確的信息後重新注冊</li><li>聯系網站管理員</li>") };
          return RedirectToAction("Error", "Prompt", _e);
        }
      }
      else
      {
        ModelState.AddModelError("Password", "原密碼不正確,請重新輸入");
        return View();
      }
      
    }

在上面的代碼中用到了一個UserName屬性,這個是在UserController添加的屬性用於返回Cookie中保存的用戶名 

/// <summary>
    /// 獲取用戶名
    /// </summary>
    public string UserName { 
      get {
        HttpCookie _cookie = Request.Cookies["User"];
        if (_cookie == null) return "";
        else return _cookie["UserName"];
        }
    }

好了,浏覽器中預覽一下

 

測試一下,OK,大功告成!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved