MVC AJAX.BeginForm() 页面异步提交

1、首先新建一个修改密码的的视图模型(viewmodel)

using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace BM.Model
{
    public class PasswordModel
    {
        /// <summary>
        /// 原密码
        /// </summary>
        [DisplayName("初始密码")] // 显示名字
        [Required(ErrorMessage = "初始密码密码不能为空")] // 不能为空特性
        [Remote("CheckPasswordIsOk", "User", ErrorMessage = "初始密码不正确", HttpMethod = "GET")] // 远程验证 User控制器下的 CheckPasswordIsOk 下去验证
        //[DataType(DataType.Password)]
        public string Password { get; set; }
        /// <summary>
        /// 新密码
        /// </summary>
        [DisplayName("新 密 码")]
        [Required(ErrorMessage = "新密码不能为空")]
        public string NewPassword { get; set; }
        /// <summary>
        /// 确认密码
        /// </summary>
        [DisplayName("确认密码")]
        [System.ComponentModel.DataAnnotations.Compare("NewPassword", ErrorMessage = "新密码不匹配")] // 比较字段
        public string ConfirmPassword { get; set; }
    }
}

2、 新建一个强类型视图

@{
    Layout = null;
}
@model  BM.Model.PasswordModel
<!DOCTYPE html>
<html>
<head>
    <title>修改密码</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="~/Content/layer/skin/layer.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>  // 这里需要注意的是: 使用Ajax.BeginForm提交表单是一定需要它,不然提交成功需要执行的js代码无法执行
    <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
    <script src="~/Content/layer/layer.js"></script>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .title {
            display: inline-block;
            width: auto;
            height: 34px;
            font-size: 22px;
            font-family: "宋体";
            font-weight: 500;
            /*color: #fff;
            background-color:#0094ff;*/
        }

        .row {
            margin: 8px;
        }

            .row input[type=text], .row input[type=password] {
                width: 300px;
                height: 30px;
                border: 1px solid #ddd;
            }

            .row input[type=submit] {
                text-align: center;
                line-height: inherit;
                width: 150px;
                height: 40px;
                font-size: 26px;
                margin-left: 80px;
                margin-top: 3px;
                color: #fff;
                background-color: #0094ff;
            }

        .field-validation-error {
            color: red;
            display: block;
        }
    </style>
</head>
<body>
    <div class="content">
        <h2 style="text-align:center">修改密码</h2>
        <div class="form">
            @using (@Ajax.BeginForm("ChangePassword", "User", new AjaxOptions() { InsertionMode = InsertionMode.Replace, HttpMethod = "POST", OnComplete = "complete" }, new { id = "form" }))
            {
                @Html.AntiForgeryToken();  // 防止CSFR 攻击,配合控制器上的 ValidateAntiForgeryToken 一起使用
                <div class="row">
                    <span class="title">@Html.DisplayNameFor(c => c.Password):</span> @Html.PasswordFor(c => c.Password)
                    @Html.ValidationMessageFor(c => c.Password)
                </div>
                <div class="row">
                    <span class="title">@Html.DisplayNameFor(c => c.NewPassword):</span> @Html.PasswordFor(c => c.NewPassword)
                    @Html.ValidationMessageFor(c => c.NewPassword)
                </div>
                <div class="row">
                    <span class="title">@Html.DisplayNameFor(c => c.ConfirmPassword):</span> @Html.PasswordFor(c => c.ConfirmPassword)
                    @Html.ValidationMessageFor(c => c.ConfirmPassword)
                </div>
                <div class="row">
                    <input id="btnSubmit" type="submit" value="确  认" />
                </div>
            }
        </div>
    </div>
</body>

</html>
<script>
    function complete(data) {
        var json = JSON.parse(data.responseText);
        layer.msg('恭喜你,密码修改成功,请重新登录!!', {
            time: 3000,
            icon: 1
        });
        setTimeout(function () {
            window.top.location.href = json.BackUrl;
        }, 2000);
    }
</script>

3. 以下是控制器中方法

 /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ChangePassword()
        {
            if (Session[CurrentUser] == null)
            {
                return Redirect("/user/login");
            }
            return View();
        }


        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult ChangePassword(PasswordModel model)
        {
            using (BusinessManageEntities db = new BusinessManageEntities())
            {
                int userId = (int)Session[CurrentUser];
                var bm = db.BusinessManager.Where(c => c.UserId == userId).FirstOrDefault();
                bm.BizPassword = Utils.Md5(model.NewPassword);
                db.SaveChanges();
            }
            //return Content("<script>base.AlertTip('修改密码成功');window.location.href='/user/login';</script>");
            return Json(new { Message = "修改密码成功", BackUrl = "/user/login" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 检查用户密码是否正确
        /// </summary>
        /// <param name="Password">旧密码</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult CheckPasswordIsOk(string password)
        {
            if (Session[CurrentUser] == null)
            {
                return Redirect("/user/login");
            }
            int userId = (int)Session[CurrentUser];
            using (BusinessManageEntities db = new BusinessManageEntities())
            {
                var bm = db.BusinessManager.Where(c => c.UserId == userId).FirstOrDefault();
                if (bm.BizPassword.Equals(Utils.Md5(password)))
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            return Json(false, JsonRequestBehavior.AllowGet);
        }

 

posted on 2015-12-17 16:48  Mr.YM  阅读(457)  评论(0编辑  收藏  举报

导航