回发后的页面客户端验证问题

时间:2015-11-04 19:12:53

标签: c# jquery asp.net

我在回发后遇到了客户端验证的奇怪问题。我更改了导致选定索引事件的Combobox项目(发生了回发)。我点击了' Save'此事件后的按钮。客户端验证没有被调用,而是调用服务器端btnSave_Click事件。 如果我不改变ComboBox,客户端验证工作正常。我想在调用服务器端方法之前在客户端验证页面控件。请告诉我。

    <asp:TextBox runat="server" ID="txtTitle" /> 
     <telerik:RadComboBox ID="RadComboBox1" runat="server" DataValueField="location_id"
                    DataTextField="description" OnSelectedIndexChanged="RadComboBox1_SelectedIndexChanged"
                    AutoPostBack="true" Width="250px" >
     </telerik:RadComboBox>

<asp:Button ID="btnSave" name="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" CausesValidation="true"/>

代码背后:

protected void RadComboBox1_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        //some logic
    }

   protected void btnSave_Click(object sender, System.EventArgs e)
    {
         // save control values
    }

客户端脚本

<script type="JavaScript">
        $("#<%=btnSave.ClientID %>").click(function () {
            //  debugger;
            var valid = true;
            var errors = false;
            var msg;
            var msg = "<b>Please fill the Required fields:</b><br />";
            if ($("#<%= txtTitle.ClientID %>").val().length == 0) {
                msg += "Title is Required!\n";
                errors = true;
            }
            if(errors){
             alert(msg);
            }
        });
    });
</script>

2 个答案:

答案 0 :(得分:2)

您的javascript验证方法无法阻止回发事件的触发。

试试这个:

<script type="JavaScript">
        $("#<%=btnSave.ClientID %>").click(function (evt) {
            //  debugger;
            var valid = true;
            var errors = false;
            var msg;
            var msg = "<b>Please fill the Required fields:</b><br />";
            if ($("#<%= txtTitle.ClientID %>").val().length == 0) {
                msg += "Title is Required!\n";
                errors = true;
            }
            if(errors){
             evt.preventDefault();
             alert(msg);
             return false;
            }
        });
    });
</script>

答案 1 :(得分:1)

由于表单控件位于UpdatePanel,因此回发会导致附加到这些控件的事件处理程序丢失。使用jQuery的事件委托来确保事件仍然触发,即使在部分回发之后也是如此。

  

Delegated events的优势在于,他们可以处理稍后添加到文档中的后代元素中的事件。通过选择附加委托事件处理程序时保证存在的元素,您可以使用委派事件来避免频繁附加和删除事件处理程序。

将您的事件处理程序附件更改为以下内容:

$('body').on('click', '#<%=btnSave.ClientID %>', function () {
    // rest of code
}

我使用body作为初始选择器,但您可以选择不在UpdatePanel内的任何其他选择器。

相关问题