mvc ajax表单验证在'post'

时间:2017-04-05 14:11:43

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

我已经打了一段时间,我觉得我很接近。我是MVC的新手,并且在网页设计的mcguffin之后,所有的模型处理(包括验证)与部分视图(不更新整个页面)。 我当前的方法(下面)'工作',直到有一个ajax回发(我使用ajax获得部分返回)。 问题是在我按下“创建”按钮并重新填充“局部视图”之前,客户端验证工作正常。我通过清除'Age'文本框并按Create来测试它。我收到消息说该字段是必需的。然后我在字段中输入一个有效值,然后再次按“创建”并“返回”。现在,当我再次清除Age框时,错误消息不会显示,它让我发布一个无效值显示。 任何人都可以告诉我为什么在点击'Create'(id = yourSubmitButtonID)按钮后它不起作用?

此外,如果有人知道更好的方法,请告诉我。

PartialController.cs

using StuffTesterMVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace StuffTesterMVC.Controllers
{
    public class PartialController : Controller
    {
        // GET: Partial
        public ActionResult Partials()
        {
            return View();
        }

        public PartialViewResult GetModel01()
        {
            PartialViewModel01 model = new PartialViewModel01();
            model.Birthday = DateTime.Parse("9/10/1964");
            return PartialView("PartialViewModel01", model);
        }
    }
}

Partials.cshtml

@{
    Layout = null;
}

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

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Partials</title>
</head>
<body>
    <div id="divPartial01"> 
        @Html.Partial("PartialViewModel01", new StuffTesterMVC.Models.PartialViewModel01())
    </div>
    @*<div id="divPartial02">
        @Html.Partial("PartialViewModel02", new StuffTesterMVC.Models.PartialViewModel02())
    </div>*@
    <!-- SCRIPTS -->
    <script>
        function saveSampleModel01() {
            alert('posting');
            $.ajax({
                url: "@Url.Action("GetModel01", "Partial")",
                type: "post",  // make this "get" to get data
                data: $("#divPartial01").serialize(),
                success: function (result) {
                    $("#divPartial01").html(result);
                    alert('success');
                },
                error: function (result) {
                    err: alert("Failed");
                }
            });
        }
    </script>
</body>
</html>

PartialViewModel01.cshtml

@model StuffTesterMVC.Models.PartialViewModel01

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>PartialViewModel01</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Birthday, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Birthday, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Birthday, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" id="yourSubmitButtonID" value="Create" class="btn btn-default" />
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" value="Save" onclick="saveSampleModel01();" class="btn btn-default" />
            </div>
        </div>
    </div>
    <script>
        $(function () {
            $("#yourSubmitButtonID").click(function (e) {
                e.preventDefault();
                var _this = $(this);
                var _form = _this.closest("form");

                alert('validating');

                var validator = $("form").validate(); // obtain validator
                var anyError = false;
                _form.find("input").each(function () {
                    if (!validator.element(this)) { // validate every input element inside this step
                        anyError = true;
                    }
                });

                if (anyError) {
                    alert('found errors');
                    return false; // exit if any error found    
                }

                alert('no errors - do "post"');
                saveSampleModel01();
                //$.post(_form.attr("action"), _form.serialize(), function (data) {
                    //check the result and do whatever you want
                })
            });
    </script>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

1 个答案:

答案 0 :(得分:0)

正如Stephen Muecke所说,我通过添加以下内容来解决这个问题:

$ validator.unobtrusive.parse(形式);

到我在PartialViewModel01.cshtml中的javascript。

我想这是一个重复的问题: Earlier question