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

时间:2017-10-06 15:42:34

标签: javascript jquery ajax asp.net-mvc-4

jQuery表单验证器可以正常使用Html.Beginform。

我将Html.Beginform更改为Ajax.Beginform以便在没有刷新的情况下提交表单(尝试了Ajax帖子,但文件在控制器中显示为null)。

更改为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>

}

控制器:

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

1 个答案:

答案 0 :(得分:0)

Firstable你还包括不引人注目的jquery验证器。您可以在输入上使用data-val html属性来自动验证字段,您的代码将更具可读性。尝试查看有关不引人注意的验证的文档。

您的问题是Ajax.BeginForm来电。请参阅visual studio auto-complete以检查方法参数。它缺少一个参数,您必须为null参数设置routeValues值,如下所示:

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