我创建了一个简单的登录表单,我想通过 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
应用程序.js
$("#login-form form").live().submit(function (e) {
e.preventDefault();
alert("ok");
});