ObjectDataSource, CustomValidators, and DataBinding

I have an ObjectDataSource object bound to a GridView. The object takes a parameter from a TextBox. The problem is that when I use ClientValidator with the ServerValidate event, the ObjectDataSource object will still try to execute the DataBind, even though the client validator returned false.

Below is the code on the aspx page.

<asp:TextBox ID="sittingDate" runat="server" />
<asp:CustomValidator ID="DateValidator" runat="server" ControlToValidate="sittingDate" OnServerValidate="DateValidator_ServerValidate" />
<asp:ObjectDataSource ID="BatchDataSource" runat="server" OldValuesParameterFormatString="original_{0}"
        SelectMethod="GetOrCreateSittingBatch" TypeName="BatchBLL" OnSelected="BatchDataSource_Selected" OnSelecting="BatchDataSource_Selecting">
        <SelectParameters>
            <asp:ControlParameter ControlID="sittingDate" Name="batchDate" PropertyName="Text"
                Type="DateTime" />
        </SelectParameters>
    </asp:ObjectDataSource>
<asp:GridView ID="BatchGridView" runat="server" DataSourceID="BatchDataSource">

In the custom validator I

protected void DateValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
        //Ensure that the entered data is a date.
        string input = args.Value;

        DateTime result;
        args.IsValid = DateTime.TryParse(input.TrimEnd(), out result);
}

How to stop ObjectDataSource from data binding after validation fails?

+3
source share
2 answers
void BatchDataSource_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
    if(!Page.IsValid)
        e.Cancel = true;
}
+3
source

Try executing Page.Validate and then check if the Page.IsValid file is to prevent data binding, for example:

this.Page.Validate();
if (this.Page.IsValid)
{
   ...
}

Page_Load , , ObjectDataSource OnDataBinding, , Page.IsValid .

0

Source: https://habr.com/ru/post/1733101/


All Articles