【问题标题】:How do I prevent EntityDataSource to execute a query if controlparameters are invalid?如果控制参数无效,如何防止 EntityDataSource 执行查询?
【发布时间】:2010-02-23 12:55:31
【问题描述】:

在 ASP.NET 网页上,我有一个 EntityDataSource:

<asp:EntityDataSource ID="EntityDataSourceOrders" runat="server" 
        ConnectionString="name=EntitiesContext"
        DefaultContainerName="EntitiesContext" 
        EntitySetName="Order" 
        Select="it.OrderID,it.OrderCode,it.OrderDateTime"
        Where="it.OrderDateTime &gt;= @DateTimeFrom AND it.OrderDateTime &lt;= @DateTimeTo"
        OrderBy="it.SOrderCode"
        StoreOriginalValuesInViewState="False" >
        <WhereParameters>
            <asp:ControlParameter Name="DateTimeFrom" 
                                  ControlID="TextBoxDateTimeFrom"
                                  DbType="DateTime"
                                  PropertyName="Text" />
            <asp:ControlParameter Name="DateTimeTo"
                                  ControlID="TextBoxDateTimeTo"
                                  DbType="DateTime"
                                  PropertyName="Text" />
        </WhereParameters>
</asp:EntityDataSource>

如您所见,页面上有两个文本框可以输入我选择的最早和最晚日期。这些文本框在 EntityDataSource 的 Where 子句中用作 ControlParameters。

现在假设有人在其中一个 ControlParameter 文本框中输入了无效日期,例如“32/01/2010”。

我知道我可以首先在客户端进行验证(使用 ASP.NET 验证器),因此如果输入无效,我会阻止回发。

但是如何在服务器端实现更重要的“最终”验证?特别是我在哪里(哪个方法或事件)实现它以防止 EntityDataSource 在文本框中使用无效的 DateTime 值执行查询?

基本上,我的想法是先调用Page.Validate(),然后再调用Page.IsValid,如果 IsValid 返回 false,则“取消”EntityDataSource 查询执行(或完全阻止它启动)。但我不知道我可以在何处或在哪个事件中连接到 EntityDataSource 以阻止查询执行。

也许我想错了方向。有人知道该怎么做吗?

提前感谢您的帮助!

【问题讨论】:

    标签: asp.net entity-framework validation entitydatasource


    【解决方案1】:

    检查有效性不是 EntityDataSource 的责任。当页面上有“保存”按钮时,单击按钮后面的代码可以检查Page.IsValid。当您使用标准 ASP.NET 控件(例如 GridView)时,这些控件将为您调用 Page.IsValid

    所以在您的情况下,我会在页面上使用 ASP.NET 验证控件。它们也将在服务器端运行。

    [更新]

    当页面无效时,您可以将方法连接到EntityDataSource.Selecting 事件并将EntityDataSourceSelectingEventArgsCancel 属性设置为true。

    private void EntityDataSourceOrders_Selecting(
        object sender, EntityDataSourceSelectingEventArgs e)
    {
        e.Cancel = !this.Page.IsValid;
    }
    

    【讨论】:

    • @Steven:我理解你的提议。但我的问题是,如果验证失败,我不知道该怎么办。例如:在您提到的 ButtonClick 事件中,我检查了Page.IsValid,它返回 false。现在怎么办?我现在想告诉 EntityDataSource 不要使用那些无效日期运行查询。 (相反,用户首先应更正日期。)目前我能想到的唯一方法是清除文本框。否则,如果我不这样做,EntityDataSource 的 ControlParameter 集合会“自动”从 TextBoxes 中提取无效日期并引发异常。
    • 太棒了!这正是我一直在寻找的!如此简单,令人尴尬的是我没有看到那个事件。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多