gpt4 book ai didi

javascript - 在 MVC 中 Ajax.BeginForm 的 onBegin 方法中使用 jQuery 表单验证器

转载 作者:行者123 更新时间:2023-11-28 04:07:03 30 4
gpt4 key购买 nike

jQuery 表单验证器与 Html.Beginform 配合良好。

我将 Html.Beginform 更改为 Ajax.Beginform,以便在不刷新的情况下提交表单(尝试过 Ajax post,但文件在 Controller 中为空)。

更改为 Ajax.Beginform 后,jQuery 表单验证器无法正常工作。

是否可以在 Ajax.Beginform 的 onBegin 方法中使用 jQuery 表单验证器?

查看:

<script src="~/scripts/jquery-1.10.2.min.js"></script>
<script src="~/scripts/jquery.validate.min.js"></script>
<script src="~/scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/scripts/jquery.unobtrusive-ajax.min.js"></script>

@using (Ajax.BeginForm("Index", "Home", new AjaxOptions { OnSuccess = "Success", OnFailure = "Failure", OnBegin = "validate", HttpMethod = "post" }, new { @Id = "form", enctype = "multipart/form-data" }))
{
<script>
function Success(data) {
alert(data);
}
function Failure() {
alert("failure");
}
function validate() {
$(document).ready(function () {
$("#form").validate({
rules: {
text1: {
required: true,
},
text2: {
required: true,

}
},
messages: {
text1: {
required: "enter text1"
},
text2: {
required: "enter text2"
},
}

});
if ($("#form").valid()) {
return true;
}
else {
return false;
}
});

}
</script>

<div>
<input type="text" id="text" name="text" />
</div>
<div>
<input type="text" id="text1" name="text1" />
</div>
<div>
<input type="submit" id="submit" name="submit" />
</div>

}

Controller :

public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(FormCollection formcollection)
{
return Json("1");
}
}

最佳答案

首先,您还包括不显眼的 jquery 验证器。您可以在输入上使用 data-val html 属性来自动验证字段,并且您的代码将更具可读性。尝试查看有关不显眼的验证的文档。

您的问题是 Ajax.BeginForm 调用。请参阅 Visual Studio 自动完成来检查方法参数。它缺少一个参数,您必须为 routeValues 参数设置一个 null 值,如下所示:

@using (Ajax.BeginForm("Index", "Home", null, new AjaxOptions { OnSuccess = "Success", OnFailure = "Failure", OnBegin = "validate", HttpMethod = "post" }, new { @Id = "form", enctype = "multipart/form-data" }))

关于javascript - 在 MVC 中 Ajax.BeginForm 的 onBegin 方法中使用 jQuery 表单验证器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46609375/

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