How to enable filtering on an ObjectDataSource with FilterExpression when bound to a List<object>.
Does anyone know how to use FilterExpression
with an ObjectDataSource
when it is bound using a select method that returns a list of entity objects?
I get the following error when I attempt it:
"The data source 'testODS' only supports filtering when the SelectMethod returns a DataSet or a开发者_开发技巧 DataTable"
According to MSDN
The ObjectDataSource control supports filtering data only when the Select method returns a DataSet or DataTable object.
So if you want to filter your result set of entities, perhaps you can use a LinqDataSource
instead.
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="MyNamespace.MyDataContext"
Select="new (MyId, MyProperty1, MyCollection1.MyProperty2)"
TableName="MyTable" Where="MyProperty1.Contains(@PropertyFilter)" >
<WhereParameters>
<asp:ControlParameter ControlID="txtPropertyFilter" Name="PropertyFilter"
PropertyName="Text" Type="String" />
</WhereParameters>
</asp:LinqDataSource>
Why not just do what the error says and use a DataTable or DataSet?
Convert generic list to dataset in C#
Use a select parameter for the ODS to hold the filter variable.
<asp:ObjectDataSource ID="odsResults" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetSearchResults"
TypeName="LiftSearchResults" SortParameterName="sortType">
<SelectParameters>
<asp:Parameter Name="liftID" Type="Int32" />
<asp:Parameter Name="sortType" Type="String" />
<asp:Parameter Name="range" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
Data object method:
[DataObjectMethod(DataObjectMethodType.Select, false)]
public List<SearchResultsLift>
GetSearchResults(
int liftID,
string sortType,
int range
)
{
List<SearchResultsLift> returnList =
new List<SearchResultsLift>();
...Code to populate list...
if (range != 0)
returnList = FilterByRange(returnList, range);
returnList = GetListSort(returnList, sortType);
return returnList;
}
Unless the range parameter is explicitly set in the page it returns 0 and all records are returned. GetListSort (not shown) is a sort function.
private List<SearchResultsLift>
FilterByRange(List<SearchResultsLift> filterList, int range)
{
var fList = (from srl in filterList
where
srl.DistanceFromDestination <= range &&
srl.DistanceFromStart <= range
select srl).ToList<SearchResultsLift>();
return fList;
}
}
精彩评论