Add WhereParameters to LinqDataSource in Selecting event
I have a repeater using a LinqDataSource as a data source. When a query string is entered, I'd like to filter the results, but ONLY when a query string is entered. If there is no query string, the results should not be filtered, all results should be returned.
I'm trying to add a WhereParameter to my LinqDataSource in the Selecting event of the LinqDataSource, but it's not working. Here's my code:
protected void ldsImages_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
if (Request.QueryString["id"] != null)
{
e.WhereParamete开发者_如何学Crs.Add("ImageTypeID", Request.QueryString["id"]);
}
}
Adding an onload event to handle the LinqDataSource_*_Load() to the LinqDataSource seems to let you to do the following:
protected void ldsAssets_Draft_Load(object sender, EventArgs e) {
string Where_Statement = " Planner_ID == @Planner_ID";
ldsAssets_Draft.WhereParameters.Add("Planner_ID", System.Data.DbType.Int32, User_ID.ToString());
if (this._DraftOrderStatus != BusinessLogic.DraftOrderStatus.All) {
Where_Statement += " AND Status_ID == @Status_ID";
ldsAssets_Draft.WhereParameters.Add("Status_ID", System.Data.DbType.Int32, ((int)this._DraftOrderStatus).ToString());
}
ldsAssets_Draft.Where = Where_Statement;
}
Since it's called on the load of the object, and not the selecting--you can still use your object with out much code behind.
Are you sure the Request.QueryString["id"] value is not null?
Are you setting the AutoGenerateWhereClause property to "true" on your LinqDataSource?
Read the Remarks section of the WhereParameters documentation page carefully.
I've never used a LinqDataSource, but could you not query your results as shown here? (Code extract from the site):
protected void LinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
var cities = from city in citiesArray
where city.CompareTo("B") > 0
select city;
e.Result = cities;
}
Therefore, you'd have something like:
protected void LinqDataSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
if(Request.QueryString["id"] != null)
{
var myImage = from img in imageSource
where img.ID == Request.QueryString["id"]
select img;
e.Result = myImage;
}
else
{
e.Result = imageSource;
}
}
A few things to note. First, this is untested :D. Second, if your ID is an integer, don't forget to cast the querystring as an integer. Finally, you should be sanitizing the querystring before using it. Although it may not be a major problem here, it's good practise.
In the markup for the LinqDataSource
you still need to declare the parameter in the Where
property of the asp:LinqDataSource
tag.
Example:
<asp:LinqDataSource ID="LDS_Images" runat="server"
ContextTypeName="DataContext" TableName="ImagesTable"
Where="ImageTypeID == @ImageTypeID ...>
...
</asp:LinqDataSource>
精彩评论