ASP.NET Custom Validator and AJAX

孤街浪徒 提交于 2019-12-23 04:42:01

问题


I implemented a Custom Validator with AJAX, and It works fine:

EDITED. Add ASPX code

<asp:DetailsView ID="DetailsView" runat="server" Height="50px" Width="25em" DataSourceID="SqlDataSource1" AutoGenerateRows="False" DefaultMode="Insert" CellPadding="4" ForeColor="#333333" GridLines="None" OnItemInserting="DetailsView_ItemInserting">
        <Fields>
            <asp:TemplateField HeaderText="Nombre *">
                <InsertItemTemplate>
                    <asp:TextBox ID="txtNombre" runat="server" Text='<%# Bind("nombre) %>'></asp:TextBox>
                    <asp:RequiredFieldValidator ID="requireNombre" runat="server" ControlToValidate="txtNombre" ErrorMessage="El campo 'Nombre' no puede estar vacío." ValidationGroup="DetailsGroup" Display="None"></asp:RequiredFieldValidator>
                    <asp:CustomValidator id="CustomValidator1" ControlToValidate="txtNombre" ClientValidationFunction="validateNombre" ValidationGroup="DetailsGroup" Display="none" ErrorMessage="Introduzca un nombre diferente." runat="server"/>
                </InsertItemTemplate>
            </asp:TemplateField>
        </Fields>
    </asp:DetailsView>

Function AJAX:

        function validateNombre(src, args) {
        var isValid;
        $.ajax({
            type: "POST",
            url: "Nombre.aspx/ComprobarNombre",
            data: "{'nombre': '" + args.Value + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (msg) {
                isValid = msg.d;
            }
        });
        args.IsValid = isValid;

ComprobarNombre: [WebMethod()]

    public static bool ComprobarNombre(string nombre)
        {
            /* SQLConnections... */

            if(...)
                 return false;
            else
                 return true;
        }

The problem is that the AJAX function is launched when every time I enter a value in the TextBox. I need that the function launch only when I click the button of the form.


回答1:


1) Eliminate Custom validator 2) On button click call client side function validateNombre() 3) Fetch the textbox data inside the function 4) and pass it in as data parameter



来源:https://stackoverflow.com/questions/17162742/asp-net-custom-validator-and-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!