微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 jQuery ajax 在 asp.net MVC 中使用引导程序和部分视图注册页面

如何解决使用 jQuery ajax 在 asp.net MVC 中使用引导程序和部分视图注册页面

我正在尝试使用引导弹出模型在 asp.net MVC 中构建一个注册页面。我正在使用局部视图来呈现我的弹出模型。我成功打开了弹出模型,数据也正在发布。但是,当控制器发送任何错误消息时,弹出模型并未打开,而是显示部分视图。

下面是控制器代码

[AllowAnonymous]
    public ActionResult Register()
    {
        return PartialView();
    }
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(UserRegisterviewmodel model)
    {
        if (ModelState.IsValid)
        {
            var result = await accountsHeplers.RegisterHelper(model);
            if (result.Status == Enums.AccountsReturnStatus.Success)
            {
                await SignInManager.SignInAsync(result.User,isPersistent: false,rememberbrowser: false);
                var cart = CartHelpers.GetCart(this.HttpContext);
                cart.MigrateFoodItemCart(db.Users.Where(p => p.Email == result.User.Email).FirstOrDefault().Id);
                return RedirectToAction("Index","Home");
            }
            else if (result.Status == Enums.AccountsReturnStatus.requiredEmailConfirmation)
            {
                return RedirectToAction("EmailVerificationMessage");
            }
            else if (result.Status == Enums.AccountsReturnStatus.UserAlreadyExist)
            {
                ModelState.AddModelError("",result.ReturnMessage);
                return PartialView(model);
            }
            else
            {
                ModelState.AddModelError("",result.IdentityResult.Errors.FirstOrDefault());
                return PartialView(model);
            }
        }

        // If we got this far,something Failed,redisplay form
        return PartialView(model);
    }

以下是我的局部视图

@model HomeMadeFoodDeliverySystem.Models.UserRegisterviewmodel

<div class="modal-dialog modal-lg">
<div class="modal-content">
    <div class="row justify-content-center">
        <div class="col-10 text-center p-0 mt-3 mb-2">
            <div class="card px-0 pt-4 pb-0 mt-3 mb-3">
                <h2 id="heading">Register</h2>
                @using (Html.BeginForm("Register","Account",FormMethod.Post,new { @class = "form-horizontal",role = "form",id = "msform",name = "msform" }))
                {
                    @Html.AntiForgeryToken()
                    <!-- progressbar -->
                    @Html.ValidationSummary("",new { @class = "text-danger" })
                    <fieldset>
                        <ul id="progressbar" class="">
                            <li class="active justify-content-center text-center" id="account"><strong>What should be call you?</strong></li>
                        </ul>
                        <div class="form-card">
                            <label class="fieldlabels">First name: *</label>
                            @Html.EditorFor(model => model.FirstName,new { htmlAttributes = new { @class = "form-control",@placeholder = "First Name" } })
                            @Html.ValidationMessageFor(model => model.FirstName,"",new { @class = "text-danger" })<br />
                            <label class="fieldlabels">Last name: *</label>
                            @Html.EditorFor(model => model.LastName,@placeholder = "Last Name" } })
                            @Html.ValidationMessageFor(model => model.LastName,new { @class = "text-danger" })<br />
                        </div>
                        <input type="button" name="next" class="next action-button" value="Next" />
                    </fieldset>
                    <fieldset>
                        <ul id="progressbar">
                            <li class="active" id="personal"><strong>How do we contact you?</strong></li>

                        </ul>
                        <div class="form-card">
                            <label class="fieldlabels">Email: *</label>
                            @Html.EditorFor(model => model.Email,@placeholder = "Email" } })
                            @Html.ValidationMessageFor(model => model.Email,new { @class = "text-danger" })<br />
                            <label class="fieldlabels">Phone number: *</label>
                            @Html.EditorFor(model => model.PhoneNumber,@placeholder = "Phone Number (03XXXXXXXXX)" } })
                            @Html.ValidationMessageFor(model => model.PhoneNumber,new { @class = "text-danger" })<br />
                        </div>
                        <input type="button" name="next" class="next action-button" value="Next" />
                        <input type="button" name="prevIoUs" class="prevIoUs action-button-prevIoUs" value="PrevIoUs" />
                    </fieldset>
                    <fieldset>
                        <ul id="progressbar">
                            <li class="active" id="payment"><strong>Where do we deliver your food?</strong></li>
                        </ul>
                        <div class="form-card">
                            <label class="fieldlabels">Address:</label>
                            @Html.EditorFor(model => model.Address,@placeholder = "Address" } })
                            @Html.ValidationMessageFor(model => model.Address,new { @class = "text-danger" })<br />
                        </div>
                        <input type="button" name="next" class="next action-button" value="Next" />
                        <input type="button" name="prevIoUs" class="prevIoUs action-button-prevIoUs" value="PrevIoUs" />
                    </fieldset>
                    <fieldset>
                        <ul id="progressbar">
                            <li class="active" id="confirm"><strong>Lets keep your account Secure</strong></li>
                        </ul>
                        <div class="form-card">
                            <label class="fieldlabels">Password:*</label>
                            @Html.EditorFor(model => model.Password,@placeholder = "Password" } })
                            @Html.ValidationMessageFor(model => model.Password,"Minimum 8 character including 1 uppercase,1 lowercase,1 number,and 1 special character",new { @class = "text-danger" })<br />
                            <label class="fieldlabels">Confirm password:*</label>
                            @Html.EditorFor(model => model.ConfirmPassword,@placeholder = "Confirm Password" } })
                            @Html.ValidationMessageFor(model => model.ConfirmPassword,new { @class = "text-danger" })<br />
                        </div>
                        <input type="submit" id="btn-register-submit" name="btn-register-submit" class="action-button" value="Register" />
                        <input type="button" name="prevIoUs" class="prevIoUs action-button-prevIoUs" value="PrevIoUs" />
                    </fieldset>
                }
            </div>
        </div>
    </div>
</div>

这是我的弹出模型的样子。

我正在使用 jQuery,如下所示

$(document).ready(function () {
    $('#msform').submit(function () {
        $.ajax({
            url: this.action,type: this.method,data: $(this).serialize(),success: function (result) {
                $('#registermodel').html(result);
                $('#registermodel').show();
            },error: function (result) {
                $('#registermodel').html(result);
                $('#registermodel').show();

            }
        });
    });
});

打开弹出模型的实例,它显示如下图所示的部分视图。

所以我的问题是如果用户已经填写的数据发生任何错误,如何再次打开弹出模型。我非常感谢您的帮助。

解决方法

我想通了。我们需要使用 Ajax.BeginForm 成功和失败的 AjaxOptions。

 @using (Ajax.BeginForm("Register","Account",FormMethod.Post,new AjaxOptions
                {
                    HttpMethod = "POST",OnSuccess = "success",OnFailure = "failure",},new { @class = "form-horizontal",role = "form",id = "msform",name = "msform" }))
                {
   ... rest of the form goes here
  }

Jquery 将如下所示。

   function success(data,status,xhr) {
    $('#registermodel').modal('hide');
    window.location.href = data.RedirectUrl;
}

function failure(xhr,error) {
    $('#registermodel').html(xhr.responseText);
    $('#registermodel').modal('show');
}

下面是控制器代码。这里我们需要返回状态码来告诉ajax调用是触发失败还是触发成功方法。

  [AllowAnonymous]
    public ActionResult Register()
    {
        return PartialView();
    }
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(UserRegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            var result = await accountsHeplers.RegisterHelper(model);
            if (result.Status == Enums.AccountsReturnStatus.Success)
            {
                await SignInManager.SignInAsync(result.User,isPersistent: false,rememberBrowser: false);
                var cart = CartHelpers.GetCart(this.HttpContext);
                cart.MigrateFoodItemCart(db.Users.Where(p => p.Email == result.User.Email).FirstOrDefault().Id);
                return RedirectToAction("Index","Home");
            }
            else if (result.Status == Enums.AccountsReturnStatus.RequiredEmailConfirmation)
            {
                return Json(new { RedirectUrl = Url.Action("EmailVerificationMessage") });
            }
            else if (result.Status == Enums.AccountsReturnStatus.UserAlreadyExist)
            {
                Response.StatusCode = 400;
                ModelState.AddModelError("",result.ReturnMessage);
                return PartialView(model);
            }
            else
            {
                Response.StatusCode = 400;
                ModelState.AddModelError("",result.IdentityResult.Errors.FirstOrDefault());
                return PartialView(model);
            }
        }
        Response.StatusCode = 400;
        // If we got this far,something failed,redisplay form
        return PartialView(model);
    }

您可以参考以下链接了解更多信息。 https://stackoverflow.com/a/31525651/7056354

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。