Search code examples
c#asp.netquery-stringdatasourcelinqdatasource

Redirect on invalid QueryStringParameter to LinqDataSource


I have the following LinqDataSource:

<asp:LinqDataSource ID = "agreementDs"
                    ContextTypeName = "AdministrationDataContext"
                    TableName = "Agreements"
                    runat = "server"
                    EnableUpdate = "true"                        
                    Where = "AgreementId=@AgreementId">

    <WhereParameters>
        <asp:QueryStringParameter QueryStringField = "AgreementId" 
                                  Name = "AgreementId"
                                  Type = "Int32"
                                  DefaultValue = "-1" />
    </WhereParameters>                        
</asp:LinqDataSource>    

It is supposed to fetch one row from the agreements database table. How can I detect if the parameter AgreementId is -1 and if so either serve up a 404 page or redirect the user to the front page of my site? I cant figure out what the correct place is to insert this logic in the code-behind.

Update: It is not only when the AgreementId parameter is -1 that the user should be redirected. It should always happen when the data source does not contain any rows.


Solution

  • Add an "OnSelecting" method name to your LINQ Data Source, then from that method, check for whatever you need:

    <asp:LinqDataSource runat="server" OnSelecting="ldsSelecting" .... />
    
    protected void ldsSelecting(object o, LinqDataSourceSelectEventArgs e)
    {
         // check for query string or other stuff here, redirect if needed
    }