繁体   English   中英

mvc3 ajax服务器端验证

[英]mvc3 ajax server side validation

我创建了一个简单的登录表单,希望通过ajax进行验证。

显示MVC产生的服务器端验证错误的最合适方法是什么? 将错误转换为JSON结果并去除错误消息是否合适? 如果没有,那会是什么?

目前,我所发布的内容正确无误,但整个表单又回来了。 目的只是在不回发/刷新的情况下在表单上显示服务器端错误。 在此先感谢...这是我的代码:

主视图-Login.vbhtml

@ModelType UHCO_MVC_Agency.LoginModel

<div class="error-container">@Html.ValidationSummary(True)</div>
<div class="row-fluid">
    <div class="span12">
        <div id="login-form" class="span6">
            @Using Html.BeginForm()
               @<fieldset>
                  <legend>Log in to your account now</legend>
                  <div class="row-fluid">
                     <div class="span12">
                        @Html.LabelFor(Function(m) m.UserName)
                        @Html.TextBoxFor(Function(m) m.UserName, New With {.class = "span12", .placeholder = "Username"})
                        @Html.ValidationMessageFor(Function(m) m.UserName)
                     </div>
                  </div>
                  <div class="row-fluid">
                     <div class="span12">
                        <label for="Password">Your password</label>
                        @Html.PasswordFor(Function(m) m.Password, New With {.class = "span12", .placeholder = "Password", .type = "password"})
                        @Html.ValidationMessageFor(Function(m) m.Password)
                     </div>
                  </div>
                  <div class="row-fluid">
                     <div class="span12">
                        <label for="RememberMe" class="checkbox clearfix">
                           @Html.CheckBoxFor(Function(m) m.RememberMe)
                           Remember me next time I visit
                        </label>
                     </div>
                  </div>
                  <button type="submit" class="btn btn-primary input-small" value="submit">Log in</button>
               </fieldset>
            End Using
         </div>
      </div>
</div>

控制器-AccountController.vb

<HttpPost()> _
Public Function Login(ByVal model As LoginModel, ByVal Username As String, ByVal Password As String, ByVal returnUrl As String) As ActionResult
   Dim res As New LoginResponse()
   Try
      'login here
   If Not String.IsNullOrEmpty(returnUrl) AndAlso Url.IsLocalUrl(returnUrl) Then
      res.Status = "Success"
      Return RedirectToAction("Welcome", "Account")
   End If
   Catch ex As Exception
      If Not HttpContext.Request.IsAjaxRequest() Then
         ModelState.AddModelError("", ExceptionWrapper.Wrap(ex).ExceptionMessage())
         Return View("Login", model)
      Else
         res.Status = "Failed"
         res.Errors.Add(ExceptionWrapper.Wrap(ex).ExceptionMessage())
         Return Json(res)
      End If
   End Try
   ' If we got this far, something failed, redisplay form
   Return View(model)
End Function

的application.js

$("#login-form form").live().submit(function (e) {
  e.preventDefault();
  alert("ok");
});

这是解决方案的C#版本。 我相信,转换为相应的VB.NET版本应该很容易

使用JSON绝对是一种不错的方法。

第一件事 我将更改POST操作方法来处理对Ajax请求的请求,并返回JSON响应。

为了保留我的错误响应,我将创建一个这样的类

public class LoginResponse
{
  public string Status { set;get;}
  public List<string> Errors { set;get;}

  public LoginResponse()
  {
    Errors=new List<string>();   
  }       
}

并在我们的POST操作方法中

[HttpPost]
public ActionResult Login(LoginModel model)
{
  if(Request.Ajax)
  {
       var res=new LoginResponse();
     //Do your Validations, If everything is fine send Success JSON
        res.Status="Success";

     //else, Lets return a JSON with errors
        res.Status="Failed";
        res.Errors.Add("Email does not exist in Earth and Mars");
        res.Errors.Add("Password contain the word black magic");

     return Json (res);
  }
  else
  {
     //Do the normal Processing for Non Ajax requests here
  }
}

因此,如果您想返回给客户端一些错误,您将以这种格式发送JSON

{
    "Status": "Failed",
    "Errors": [  "Email does not exist",  "Passoword is worse"  ]
}

如果一切正常,我们将像这样发送JSON

{
    "Status": "Success"
}

现在,在我们看来,我们将摆脱Ajax表单,并使用Normal表单标签和一些纯jQuery。

@ModelType UHCO_MVC_Agency.LoginModel
@using(Html.BeginForm())
{
  //Here your for elements

  <input type="submit" id="btnSubmit"/>
}
<script type="text/javascript">

$(function(){
   $("#btnSubmit").click(function (e) {
      e.preventDefault();
     $.post("@Url.Action("Login","User")", $("form").serialize(), function (r) {
       if(r.Status=="Success")
       {
         //Login is success . do whatever you want.
       }
       else
       {
         //Lets get the Errors from our JSON
         $.each(r.Errors,function(index,item){
             //Lets show the error
              $("#errorSummary").append(item);
         }  
       }
     });

});    
</script>

编辑:像这样更改您的js代码,看看会发生什么

$("#login-form form").live('submit', function(e){
   e.preventDefault();
  //the code

});

无论如何,我不是VB人士,但我认为您需要做的是:

1)在您的控制器中,您需要检查并查看是否已通过AJAX到达。 您既可以发送额外的信息,也可以发送数据以表明这一点,或者使用SERVER['HTTP_X_REQUESTED_WITH']并检查大多数常见库发送的XMLHTTPRequest。

2)如果实际上是通过AJAX请求页面的,那么在打包输出时可以采取不同的过程。 仅返回JSON,然后在操作DOM的客户端解析它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM