码迷,mamicode.com
首页 > Web开发 > 详细

(四)学习MVC之修改个人资料和身份验证登陆

时间:2014-08-26 01:47:15      阅读:461      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   java   os   使用   io   

1.修改密码不用建立模型,直接在UserControl.cs添加 ChangeInfo():

#region 修改用户资料
        [UserAuthorize]
        public ActionResult ChangeInfo()
        {
            userRsy = new UserRepository();
            var _user = userRsy.Find(UserName);
            return View(_user);
        }
        [HttpPost]
        [UserAuthorize]
        public ActionResult ChangeInfo(User user)
        {
            userRsy = new UserRepository();
            if (userRsy.Authentication(UserName, ModifyPasswordExample.Common.Text.Sha256(user.Password)) == 0)
            {
                var _user = userRsy.Find(UserName);
                _user.Gender = user.Gender;
                _user.Email = user.Email;
                _user.QQ = user.QQ;
                _user.Tel = user.Tel;
                _user.Address = user.Address;
                _user.PostCode = user.PostCode;
                if (userRsy.Update(_user))
                {
                    Notice _n = new Notice { Title = "修改资料成功", Details = "您已经成功修改资料!", DwellTime = 5, NavigationName = "用户首页", NavigationUrl = Url.Action("Default", "User") };
                    return RedirectToAction("UserNotice", "Prompt", _n);
                }
                else
                {
                    Error _e = new Error { Title = "修改资料失败", Details = "在修改用户资料时时,更新的资料未能保存到数据库", Cause = "系统错误", Solution = Server.UrlEncode("<li>返回<a href=‘" + Url.Action("ChangeInfo", "User") + "‘>修改资料</a>页面,输入正确的信息后重新操作</li><li>联系网站管理员</li>") };
                    return RedirectToAction("UserError", "Prompt", _e);
                }
            }
            else
            {
                ModelState.AddModelError("Password", "密码错误!");
                return View();
            }


        }
        #endregion

2.其中[UserAuthorize]特性是[Authorize]的重写,在Extensions/UserAuthorizeAttribute.cs。使用方式是直接在方法上面加这个特性就可以了。

重写后[UserAuthorize]的作用是用户权限认证,比如说直接在浏览器直接输入修改资料的Url,但是由于没有进行身份验证,需要先转到某个指定的页面,身份验证成功后自动回到修改资料的页面,在转到某个指定页面时,会将指定页面之前的Url一起传递过去,这样成功验证后就可以通过传递的Url到达指定页面前的页面。[UserAuthorize]配合的语句一般有这一句:Request.QueryString["ReturnUrl"] != null) return Redirect(Request.QueryString["ReturnUrl"]

using ModifyPasswordExample.Repository;

namespace System.Web.Mvc
{
    /// <summary>
    /// 用户权限验证
    /// </summary>
    public class UserAuthorizeAttribute :AuthorizeAttribute
    {
        /// <summary>
        /// 核心【验证用户是否登陆】
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //检查Cookies["User"]是否存在
            if (httpContext.Request.Cookies["User"] == null) return false;
            //验证用户名密码是否正确
            HttpCookie _cookie = httpContext.Request.Cookies["User"];
            string _userName = _cookie["UserName"];
            string _password = _cookie["Password"];
            if (_userName == "" || _password == "") return false;
            UserRepository _userRsy = new UserRepository();
            if (_userRsy.Authentication(_userName, _password) == 0) return true;
            else return false;
        }
    }
}

WebConfig配置中的<authentication >标签起到指定某个特定页面的作用。这里的指定页面是/User/Login         
         

<authentication mode="Forms">          
      <forms loginUrl="~/User/Login" timeout="2880" />  
    </authentication>

3.之前有使用UserControl的Default方法及相对应的视图,现重新修改,代码如下:

方法:

#region 用户中心默认页面
        /// <summary>
        /// 用户中心默认页面
        /// </summary>
        /// <returns></returns>
        [UserAuthorize]     //有加这个特性的方法将会先转到某个特定页面,这里是登录页面。和WebConfig的<authentication>标签一起使用。
        public ActionResult Default()
        {
            userRsy = new UserRepository();
            var _user = userRsy.Find(UserName);
            return View(_user);
        }

        #endregion
 

视图:

@model ModifyPasswordExample.Models.User

@{
    ViewBag.Title = "首页";
    Layout = "~/Views/Shared/_User.cshtml";
}

<div class="leftnav">
    <div class="Nav">
        @*您现在的位置: 用户首页*@
        @Html.Partial("PartialPersonalNav")
    </div>
    <div>
        @Model.UserName
        <br />
        @Model.GroupId
    </div>
</div>
Shared/_User.cshtml是一个布局视图:
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title-用户中心</title>
    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/themes/base/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render(" ~/bundles/jqueryui") 
    @Scripts.Render("~/bundles/jqueryval")

</head> <body> <div class="header"> <div class="info"></div> <div class="menubar"> <a href="@Context @Url.Action("Default", "User")">用户管理</a><a href="@Url.Action("UserDefault", "Article")">文章管理</a> </div> </div> <div class="wrapper"> @RenderBody() </div> <div class="footer"></div> </body> <script type="text/javascript"> $(".menubar a").button(); $(document).ready(function () { var _vwheight = $(document).height() - $(".header").height() - $(".footer").height();//可视的工作区域高度 var _lheight = $(".left").height(); var _wheight = $(".workspace").height(); if (_vwheight < _lheight) _vwheight = _lheight; if (_vwheight < _wheight) _vwheight = _vwheight; $(".workspace").height(_vwheight); $(".left").height(_vwheight) }); /*按钮*/ </script> </html>

4.现在要把左侧导航列表做出来,在视图的User文件夹上点右键新建局部视图PartialPersonalNav:

bubuko.com,布布扣

<ul>
    <li>@Html.ActionLink("用户首页","Default","User")</li>
    <li>@Html.ActionLink("修改信息","ChangeInfo","User")</li>
    <li>@Html.ActionLink("修改密码","ChangePassword","User")</li>
    <li>@Html.ActionLink("退出系统","Logout","User")</li>
</ul>

将default.cshtml中“这里左侧导航列表”替换为@Html.Partial("PartialPersonalNav")。

5.创建ChangeInfo的强类型视图,视图:

 

@model ModifyPasswordExample.Models.User

@{
    ViewBag.Title = "修改个人资料";
    Layout = "~/Views/Shared/_User.cshtml";
}

<div class="leftnav">@Html.Partial("PartialPersonalNav")</div>
<div class="workspace">
    <div class="Nav">您现在的位置: 用户首页</div>
    <div>
        @using (Html.BeginForm())
        {
            @Html.ValidationSummary(true)

            <fieldset>
                <legend>修改资料</legend>
                @Html.HiddenFor(model => model.UserId)
                <ul>
                    <li>
                        <div class="editor-label">
                            @Html.LabelFor(model => model.UserName)
                        </div>
                        <div class="editor-field">
                            @Html.DisplayFor(model => model.UserName)
                        </div>
                    </li>
                    <li>
                        <div class="editor-label">
                            @Html.LabelFor(model => model.Password)
                        </div>
                        <div class="editor-field">
                            @Html.Password("Password")
                            @Html.ValidationMessageFor(model => model.Password)
                            输入正确的密码才能修改资料。
                        </div>
                    </li>
                    <li>
                        <div class="editor-label">
                            @Html.LabelFor(model => model.Gender)
                        </div>
                        <div class="editor-field">
                            @Html.RadioButtonFor(model => model.Gender, 0) 男
                            @Html.RadioButtonFor(model => model.Gender, 1) 女
                            @Html.RadioButtonFor(model => model.Gender, 2) 保密
                        </div>
                    </li>
                    <li>
                        <div class="editor-label">
                            @Html.LabelFor(model => model.Email)
                        </div>
                        <div class="editor-field">
                            @Html.EditorFor(model => model.Email)
                            @Html.ValidationMessageFor(model => model.Email)
                            @Html.DisplayDescriptionFor(model => model.Email)
                        </div>
                    </li>
                    <li>
                        <div class="editor-label">
                            @Html.LabelFor(model => model.QQ)
                        </div>
                        <div class="editor-field">
                            @Html.EditorFor(model => model.QQ)
                            @Html.ValidationMessageFor(model => model.QQ)
                            @Html.DisplayDescriptionFor(model => model.QQ)
                        </div>
                    </li>
                    <li>
                        <div class="editor-label">
                            @Html.LabelFor(model => model.Tel)
                        </div>
                        <div class="editor-field">
                            @Html.EditorFor(model => model.Tel)
                            @Html.ValidationMessageFor(model => model.Tel)
                            @Html.DisplayDescriptionFor(model => model.Tel)
                        </div>
                    </li>
                    <li>
                        <div class="editor-label">
                            @Html.LabelFor(model => model.Address)
                        </div>
                        <div class="editor-field">
                            @Html.EditorFor(model => model.Address)
                            @Html.ValidationMessageFor(model => model.Address)
                            @Html.DisplayDescriptionFor(model => model.Address)
                        </div>
                    </li>
                    <li>
                        <div class="editor-label">
                            @Html.LabelFor(model => model.PostCode)
                        </div>
                        <div class="editor-field">
                            @Html.EditorFor(model => model.PostCode)
                            @Html.ValidationMessageFor(model => model.PostCode)
                            @Html.DisplayDescriptionFor(model => model.PostCode)
                        </div>
                    </li>
                    <li><input type="submit" value="修改" /></li>
                </ul>
            </fieldset>
        }
    </div>
</div>

 

6.运行程序,修改资料正常运行。

bubuko.com,布布扣

 

(四)学习MVC之修改个人资料和身份验证登陆

标签:des   style   blog   http   color   java   os   使用   io   

原文地址:http://www.cnblogs.com/wiming/p/3936293.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!