gpt4 book ai didi

asp.net - 尽管 asp.net mvc 4 验证失败,jquery post 仍然会通过

转载 作者:行者123 更新时间:2023-12-01 03:14:31 27 4
gpt4 key购买 nike

我想要一个 asp.net mvc 表单发布到 Controller ,并显示错误或成功消息,所有这些都使用 jquery。我希望仅当表单验证成功时才会发生此 jquery 帖子。在发布到服务器之前,验证应该在客户端进行。问题是,即使表单验证失败,帖子也会发生。看起来整个表格都在发回,但我不能确定这一点。我正在使用mvc框架中的数据注释来验证。这是代码

查看

@model jQueryPosts.Models.ModelVM
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.8.3.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

<div>
@using ( Html.BeginForm("jQueryPost", "Home",null, FormMethod.Post, new { id="FormPost" }))
{
@Html.TextBoxFor(x => x.Name) @Html.ValidationMessageFor(x => x.Name)
<br />
@Html.TextBoxFor(x => x.LastName) @Html.ValidationMessageFor(x => x.LastName)
<br />
@Html.TextBoxFor(x => x.Age) @Html.ValidationMessageFor(x => x.Age)
<br />

<input type=submit value="submit" />
}
</div>

<script>

$(document).ready(function () {

$('#FormPost').submit(function (e) {
e.preventDefault(); //This line will prevent the form from submitting
alert('ajax post here');

$.ajax({
type: 'POST',
url: $('#FormPost').attr('action'),
data: $('#FormPost').serialize(),
accept: 'application/json',
error: function (xhr, status, error) {

alert('error: ' + xhr.responseText + '-' + error);

},
success: function (response) {
alert('resp: ' + response);
}
});
});


});

</script>

Controller

   [AcceptVerbs(HttpVerbs.Post)]
public JsonResult jQueryPost(ModelVM vm)
{
ModelVM _vm = vm;

try
{
//some code here
}
catch
{
Response.StatusCode = 406; // Or any other proper status code.
Response.Write("Custom error message");
return null;
}

return Json("name posted was: " + _vm.Name);
}

型号

using System.ComponentModel.DataAnnotations;

namespace JQ.Example
{
public class ModelVM
{
[Required(ErrorMessage="Please enter first name") ]
public string Name { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
}
}

最佳答案

发生这种情况是因为当您按下提交的输入类型时,表单无论如何都会提交,只需尝试将 return false 添加到您的 jquery 函数

$('#FormPost').submit(function (e) {            
var validated = $("#FormPost").valid();
if(validated)
{
$.ajax({
type: 'POST',
url: $('#FormPost').attr('action'),
data: $('#FormPost').serialize(),
accept: 'application/json',
error: function (xhr, status, error) {

alert('error: ' + xhr.responseText + '-' + error);

},
success: function (response) {
alert('resp: ' + response);
}
});
}

return false;
});

将此行代码添加到 Controller

if (ModelState.IsValid)
{
...
}
else
{
ModelState.AddModelError("key", "messege");
}

关于asp.net - 尽管 asp.net mvc 4 验证失败,jquery post 仍然会通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18436284/

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