使用ajax调用的客户端验证不起作用

时间:2018-04-19 14:05:12

标签: javascript c# jquery asp.net webforms

当单击jQuery数据表中的行并使用从所选行获取的数据填充它时,我打开一个模式对话框。用户可以更新某些字段并提交。我有客户端验证;需要此类文本的基本类型,或从下拉列表中选择一些内容。

对于一个字段,我需要检查需要服务器端检查的重复值(例如重复名称)。问题是当我进行服务器端检查时,回发会关闭模式对话框。因此,对于这部分,我建议使用ajax。

按照@Rafalon的建议,我设法进行ajax调用来验证输入。但是,当调用函数valiadteSubmit()时,它会通过其他验证,然后执行ajax调用并退出,关闭模态,即使在.done()中我可以看到错误被捕获。请参阅以下内容:

<div class="modal fade" id="newModal" role="dialog" aria-labelledby="editLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg fade in ui-draggable">
        <div class="modal-content">
            <div class="modal-body">
                <div class="row">
                    <div class="col-sm-4">
                        <div class="form-group">
                            <label for="tbName">Name</label>
                            <input type="text" runat="server" id="tbName" class="form-control" clientidmode="Static" />
                            <span id="lblErrName" class="field-validation-error pull-left" style="display: inline"></span>
                        </div>
                    </div>
                    ...
                </div>
            </div>
            <div class="modal-footer">
                <div id="divNewButtons" style="text-align: center;">
                    <button id="btnCancel" class="btn btn-info2" data-dismiss="modal" aria-hidden="true" aria-label="Cancel">Cancel</button>&nbsp;&nbsp;&nbsp;&nbsp;
                    <button id="btnSubmit" class="btn btn-primary" aria-hidden="true" aria-label="Submit">Submit</button>
                </div>
        </div>
    </div>
</div>


$(document).on("click", "#btnSubmit", function (event) {
    var isValid = validateSubmit();

    if (isValid) {
        // do whatever
    }
    else
        return false;
});

function validateSubmit() {debugger
    var isValid = true;
    var name = $("#tbName").val();
    var districtID = $("#ddlDistrict").val();

    var nameErr = false;

    // this gets executed after other validations following it
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        url: '/services/mpoo.asmx/NameExists',
        cache: false,
        data: JSON.stringify({ "Name": name, "DistrictID": districtID }),
    }).done(function (data) {debugger
        nameErr = JSON.parse(data.d);  // this is "true" or "false"
        if (nameErr == 'true') {
            // This error never gets displayed because modal closes
            $("#lblErrName").text("Duplicate Name within selected District");
            $("#lblErrName").show();
            isValid = false;  // I tried "return false;"
        }
    });
    if (name == '') {
        $("#lblErrName").text("Name is required");
        $("#lblErrName").show();
        isValid = false; // also tried "return false;"
    }
    ... // other validations here
    return isValid;
}

1 个答案:

答案 0 :(得分:0)

为此,您可以使用updatepanel包围需要在模态内进行验证的控件。您可以通过简单的方式onTextChanged来触发验证

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
    Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
   <ContentTemplate>
      <asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>
      <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator" ControlToValidate="TextBox1" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
    </ContentTemplate>
    <Triggers>
       <asp:AsyncPostBackTrigger ControlID="TextBox1" />
    </Triggers>
</asp:UpdatePanel>

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

on codebehind

protected void TextBox1_TextChanged(object sender, EventArgs e)
{
    CustomValidator1.Validate();
}

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
///do the validation here return true if passes else false.
    args.IsValid = false;
}

updatepanel将阻止页面重新加载,因此模式不会关闭。这是你如何做到这一点的一个小例子。

相关问题