部分视图的AJAX模型验证



我有一个局部视图,这是一个登录功能作为一个弹出。我所要做的就是让我的模型执行验证(服务器端)并通过AJAX返回任何错误。下面的代码只返回带有错误的部分视图。我希望我的操作结果不返回视图,而只返回错误。在旧的ASP中。NET,这将是一个部分Post回来。我不确定如何在MVC中实现这一点。

这是模型

public class LoginModel
{
    [Required]
    public String Email { get; set; }
    [Required]
    [DataType(DataType.Password)]
    public String Password { get; set; }
}

这是局部视图

@model MySite.Models.LoginModel
@using (Ajax.BeginForm("Authenticate", "Account", null, new AjaxOptions { OnFailure = "error" }, new { id = "LoginForm" }))

{

<div class="modal-body" id="LoginPopupDialogMessage">
    The page you have requested requires you to login. Please enter your credentials and choose your country:
    <br />
    <br />
    <div class="row">
        <div class="form-group col-lg-offset-2 col-lg-8">
            <label>Email Address</label>
            @Html.TextBoxFor(u => u.Email, new { @class = "form-control input-lg  input-sm", id = "Email", name = "Email" })
            @Html.ValidationMessageFor(u => u.Email)
        </div>
    </div>
    <div class="row">
        <div class="form-group col-lg-offset-2 col-lg-8 ">
            <label>Password</label>
            @Html.PasswordFor(u => u.Password, new { @class = "form-control input-lg  input-sm", name = "Password" })
            @Html.ValidationMessageFor(u => u.Password)
        </div>
    </div>
    <div style="text-align: center; padding-top: 20px;" class="ImageGroup">
        <button name="companyCode" value="LB_US" class="btn-link" type="submit">
            <img src="../../WebContent/Images/icon-flag-usa.png" />
        </button>
        <button name="companyCode" value="LB_CA" class="btn-link" type="submit">
            <img src="../../WebContent/Images/icon-flag-canada.png" />
        </button>
        <button name="companyCode" value="LB_EU" class="btn-link" type="submit">
            <img src="../../WebContent/Images/icon-flag-europe.png" />
        </button>
    </div>
</div>
}

我从_layout.cshtml.调用偏视图

<div class="modal fade" id="LoginPopupDialog" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header" style="background: #e7e3e7; color:#000;">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="color:#000;">
                    <span aria-hidden="true">&times;</span>
                </button>
                <div class="modal-title" id="LoginPopupDialogHeader">Please Login</div>
             </div>
               @Html.Action("Login", "Account")
         </div>
     </div>
</div>

My Controller Action:

 [HttpPost]
 [Route("account/authenticate")]
 public ActionResult Authenticate(String companyCode, LoginModel model)
        {
    if (!ModelState.IsValid)
        {
            // ??
        }
    return PartialView("Login", model);
 }

由于您的代码正在为登录执行ajax表单提交,因此您应该尝试从服务器返回JSON响应。如果模型验证失败,您可以从模型状态字典中读取验证错误,并将其存储在字符串(错误消息)集合中,并将其作为json响应的一部分返回。如果模型验证通过,你可以继续执行你的代码来验证登录凭据,如果这些看起来不错,发回一个json响应,其中包含用户的下一个url(我们可以将用户重定向到该url)。

[HttpPost]
public ActionResult Authenticate(String companyCode, LoginModel model)
{
    if (!ModelState.IsValid)
    {
        var errors = ViewData.ModelState.Values
                             .SelectMany(x => x.Errors.Select(c => c.ErrorMessage));
        return Json(new { Status = "Error", Errors = errors });
    }
    //to do  :Verify login, if good, return the below respose
    var url=new UrlHelper(Request.RequestContext);
    var newUrl = url.Action("About");
    return Json(new { Status="Success", Url = newUrl});
}

现在在您的视图中,您可以指定一个OnSuccess处理程序作为AjaxOptions的一部分。这将是一个javascript对象,来自服务器的json响应将会到达。我们基本上需要检查Status属性值并做适当的事情。

new AjaxOptions { OnFailure = "error" , OnSuccess="loginDone"}

下面的loginDone实现只是提醒错误消息。您可以更新它以将其显示为DOM的一部分。

function loginDone(d) {
    if (d.Status === "Success") {
        window.location.href = d.Url;
    } else {
        $.each(d.Errors,function(a, b) {
                alert(b);
        });
    }
}

您还可以考虑启用不引人注目的客户端验证,它在尝试调用服务器之前进行客户端验证。这还将显示验证错误范围内的错误消息(与普通mvc模型验证相同)

最新更新