【问题标题】:How do I do validation on modal bootstrap from a controller?如何从控制器对模态引导进行验证?
【发布时间】:2015-04-23 08:17:59
【问题描述】:

我有一个使用模式引导的部分视图登录。在我在客户端验证模型后一切正常。但我想检查登录是否失败,如果是,则将错误消息从控制器返回到模式引导程序而不是回发页面。我该怎么做?

我的 _partialview 登录:

<div id="loginModal" class="modal fade">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-body">
                @using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal"}))
                {
                    @Html.AntiForgeryToken()
                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    <div class="form-group">
                        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
                        <div class="col-md-10">
                            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
                            @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
                        <div class="col-md-10">
                            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
                            @Html.ValidationMessageFor(m => m.Password, "", new { @class = "text-danger" })
                        </div>
                    </div>
                    <div style="text-align:right;">
                        <button type="submit" class="btn btn-primary btn-sm">Submit</button>
                    </div>
                }
    </div>
</div>

账户控制人

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

【问题讨论】:

    标签: ajax json asp.net-mvc controller


    【解决方案1】:

    如果我了解您希望得到错误,请在不重新加载页面的情况下将它们显示给用户。您所需要的只是使用一些 ajax,然后使用它的成功/错误函数显示错误/重定向到新页面。堆栈上也有很多示例。出于安全原因,请记住使用 HTTPS 和密码。这里有一些例子:Login Page using ASP.Net & Ajax

    【讨论】:

      【解决方案2】:

      您应该为此使用一些验证插件。这是最简单且非常受欢迎的验证 pugin jQuery Validation Plugin

      干杯!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-02
        • 2016-06-03
        • 2018-12-14
        • 2011-08-04
        • 1970-01-01
        • 2019-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多