gpt4 book ai didi

ajax - mvc3 ajax 服务器端验证

转载 作者:行者123 更新时间:2023-12-01 04:58:49 25 4
gpt4 key购买 nike

我创建了一个简单的登录表单,我想通过 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>

Controller - 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 表单,并使用普通表单标签和一些纯 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

});

关于ajax - mvc3 ajax 服务器端验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12184362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com