服务器和客户端验证在“模式”弹出式局部视图中不起作用

时间:2018-08-02 10:05:08

标签: jquery asp.net-mvc validation

我想在模式部分视图中实现服务器和客户端验证,但是即使提交文本框和链接为空白,此验证也无法正常工作。我已经在bundle下的主视图中包含了@section scripts{。当前,当我单击Save时,即使字段为空,它也会保存模态数据。

模式

    [Required(ErrorMessage ="Please enter Title")]
    public string Title { get; set; }
   [Required(ErrorMessage = "Please enter valid URL link!")]
    [Url(ErrorMessage ="Please enter valid URL link!")]
    public string Link { get; set; }

模态局部视图

请注意,表单是使用Ajax加载的

<div class="modal fade" id="EditModal" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">

            <div class="modal-body">
                @using (Html.BeginForm("_pEdit", "Home", FormMethod.Post, new { Id = "Editform"}))
                {
                    <div class="form-group">
                        @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label" })
                        @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
                    </div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Link, htmlAttributes: new { @class = "control-label" })
                        @Html.EditorFor(model => model.Link, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Link, "", new { @class = "text-danger" })
                    </div>
                }

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" id="submit-modal" class="btn btn-primary">Save</button>
            </div>
        </div>
    </div>
</div>

脚本

 $(document).on("click", '.LinkId', function (e) {
        $(this).load(actionURL, function (html) {
            // Reparse the validator
            var form = $('form');
            form.data('validator', null);
            $.validator.unobtrusive.parse(form);
            $.ajax({
                url: $(this).data("url"),
                type: "GET",
                success: function (response) {
                    if (response) {
                        $('#EditModal').replaceWith(response);
                        $('#EditModal').modal('show');                            
                    }
                    else {
                        var message = response.message;
                        alert(message);
                    }
                }
            });
            return false;
        })
        });

0 个答案:

没有答案