使用ajax进行自定义用户注册不起作用(ASP.NET MVC4)

时间:2015-11-24 15:43:47

标签: c# ajax asp.net-mvc asp.net-mvc-4

我使用SimpleCrypto library创建了自定义用户注册。它在自己的页面上工作正常(控制器UserController,操作Registration,查看Registration)。然后我想使用ajax在主页上的模态窗口中进行注册。

我创建了部分视图 _Registration.cshtml

@model TaskManager.Models.RegisterUserModel

<div class="modal fade" id="registrationModal">
  <div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h2 class="modal-title">Registration</h2>
        </div>

        @using (Html.BeginForm("Registration", "User", FormMethod.Post, new { @class = "registration-form", id = "registration-form" }))
        {
            @Html.AntiForgeryToken()
            @Html.ValidationSummary(true)

            <div class="modal-body">
                 <div class="form-group">
                    @Html.LabelFor(u => u.Name)
                    @Html.TextBoxFor(u => u.Name, new { @class = "form-control" })
                    @Html.ValidationMessageFor(u => u.Name, null, new { @class = "error" })
                </div>

                <div class="form-group">
                    @Html.LabelFor(u => u.Email)
                    @Html.TextBoxFor(u => u.Email, new { @class = "form-control" })
                    @Html.ValidationMessageFor(u => u.Email, null, new { @class = "error" })
                </div>

                <div class="form-group">
                    @Html.LabelFor(u => u.Password)
                    @Html.PasswordFor(u => u.Password, new { @class = "form-control" })
                    @Html.ValidationMessageFor(u => u.Password, null, new { @class = "error" })
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <input type="submit" class="btn btn-primary" value="Register">
            </div>
        }

    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

并将其添加到主页

<a href="#" data-toggle="modal" data-target="#registrationModal">registration</a>
@Html.Partial("~/Views/User/_Registration.cshtml")

这是我的 .js 文件

/* -------------- DOM READY -------------- */
$(document).ready(function () {
"use strict";

var $body = $("body");

var ajaxRegistration = function () {
    var $form = $(this);

    var options = {
        url: $form.attr("action"),
        type: $form.attr("method"),
        data: $form.serialize()
    };

    console.log(options);
    $.ajax(options).done(function (data) {
        console.log("ok");
    })
   .fail(function () {
       console.log("error");
   });

    return false;
};
$("#registration-form").submit(ajaxRegistration);
});

这是我的 UserController

namespace TaskManager.Controllers
{
    public class UserController : Controller
    {
        TaskManagerDbContext _db = new TaskManagerDbContext();

        [HttpGet]
        [AjaxAction]
        public ActionResult Registration()
        {
            var registerUser = new RegisterUserModel();
            return PartialView("_Registration", registerUser);
        }

        [HttpPost]
        [AjaxAction]
        public ActionResult Registration(RegisterUserModel registerUser)
        {            
            if (ModelState.IsValid)
            {
                if (!IsUserExist(registerUser.Email))
                {    

                    var crypto = new SimpleCrypto.PBKDF2();

                    var encrpPass = crypto.Compute(registerUser.Password);

                    var newUser = _db.Users.Create();

                    newUser.Name = registerUser.Name;
                    newUser.Email = registerUser.Email;
                    newUser.Type = UserType.User.ToString();

                    newUser.Password = encrpPass;
                    newUser.PasswordSalt = crypto.Salt;

                    _db.Users.Add(newUser);
                    _db.SaveChanges();

                    return RedirectToAction("Index", "Task");

                }
                else
                {
                    ModelState.AddModelError("", "User already exists");
                }
            }
            else
            {
                ModelState.AddModelError("", "Data is incorrect");
            }

            return PartialView("_Registration", registerUser);
        }

        private bool IsUserExist(string email)
        {
            bool IsValid = false;

            var user = _db.Users.FirstOrDefault(u => u.Email == email);

            if (user != null)
            {
                IsValid = true;
            }

            return IsValid;
        }

        protected override void Dispose(bool disposing)
        {
            if (_db != null)
            {
                _db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

它工作并在数据库中添加用户,如果任何表单字段无效(空数据或不正确的数据),则在模态窗口中显示错误。
但与此同时,我无法解决一些问题。

首先,如果ModelState.IsValid不正确或IsUserExist(registerUser.Email)返回true,我的表单中不会出现任何错误,ModelState.AddModelError("", "User already exists");ModelState.AddModelError("", "Неправильные данные");“工作。

第二个,如果用户注册成功,重定向return RedirectToAction("Index", "Task");不起作用,我不知道为什么。

如何修复这些错误?

1 个答案:

答案 0 :(得分:1)

一种可能的(而且相当简单)选项:在你的控制器中,你可以像

那样做
           if (ModelState.IsValid)
            {
                if (!IsUserExist(registerUser.Email))
                { 
                    // bad here
                    //return RedirectToAction("Index", "Task");
                    return new HttpStatusCodeResult(HttpStatusCode.OK); //at least
                }
                else
                {
                  return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, "User already exists");
                }
            }
            else
            {
               return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, "Data is incorrect");
            }

然后在js中说出以下内容。我使用这两个选项,成功和错误,因此您可以删除已完成的方法并失败。

var options = {
        url: $form.attr("action"),
        type: $form.attr("method"),
        data: $form.serialize()
        success: function() {/*redirect here*/},
        error: function (e) {
            alert(e.statusText); /* show the error */
        }
    };

至于重定向。同样,ajax不希望被重定向。这就是为什么在获得成功案例时需要手动重定向的原因。