当表单包含隐藏的输入字段时,不显眼的客户端验证不起作用

时间:2014-10-10 09:20:32

标签: ajax asp.net-mvc partial-views unobtrusive-validation

我有一个类似的模型:

public class Person
{
    public int ID { get; set; }

    [Required]
    public string LastName { get; set; }

    [Required]
    public string FirstMidName { get; set; }
}

观点:

@model ContosoUniversity.Models.Student

@using (Html.BeginForm("Edit", "Student", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <div class="form-horizontal">

        @Html.HiddenFor(model => model.ID)

        <div 
            @Html.LabelFor(model => model.LastName, new { @class = "control-label col-md-2" })
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div >
            @Html.LabelFor(model => model.FirstMidName, new { @class = "control-label col-md-2" })
            @Html.EditorFor(model => model.FirstMidName)
            @Html.ValidationMessageFor(model => model.FirstMidName)
        </div>

        <div>
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
}

问题是当我使用Ajax Get使用return PartialView("Edit", student);语句呈现视图时,不显眼的jQuery验证失败。当我删除隐藏字段@Html.HiddenFor(model => model.ID)时,验证工作正常。

我使用下面的代码使用Ajax Get请求呈现视图:

function ShowEditPartialView(sender) {
    $.ajax({
        type: "GET",
        url: "/Student/EditPartial",
        data: {
            id: courseid
        },
        async: false,
        success: function (data) {

            $("#EditCoursePartial").html(data);

            ///because the page is loaded with ajax, the validation rules are lost, we have to rebind them:
            $('form').removeData('validator');
            $('form').removeData('unobtrusiveValidation');
            $.validator.unobtrusive.parse('form');
        }
    });
}

有关如何解决的任何想法。

0 个答案:

没有答案