I’m trying to implement a custom filter template for all text based searches and running into problems constructing the query. I’ve been following the instructions posted on this blog but not sure how change the GetQueryable method to perform a
WHERE columnAttribute LIKE '%something%'
query. In the example on the blog the expression is an equality which works if the text I enter exactly matches the text in the database column.
At the moment I’m using the new QueryExtender feature along with the SearchExpression control but this requires creating several custom pages for all the tables I need text search functionality for. I would like to DRY this up by creating the custom filter template. Any help would be greatly appreciated.
In LINQ to SQL, the Strings.Contains method is how you express the LIKE operator. What follows is an example of how you could build a filter template around the LIKE operator. For this example, we’ll give our custom filter template the name “Text”.
The first step is to update the Dynamic Data metadata. Annotate all the columns you want to be able to search on with the FilterUIHintAttribute like so:
Now we need to create the “Text” filter template. Create the Text.ascx user control in the filter templates folder (typically “~/DynamicData/Filters”):
Next create the code behind, Text.ascx.cs:
Notice that we have provided no way for the user to postback the page (and hence, update the results) after updating the Text filter. As a matter of style, I find TextBox controls that auto-postback to be confusing, and I find that it is redundant to have a separate button to postback each individual filter. Instead, I like to add a single Button to the page template (for example, “~/DynamicData/PageTemplates/List.aspx”) that allows the user to postback the page and update the results. Here is the relevant excerpt:
That’s all there is to it. Users should now be able to search for records that contain fragments of text in the specified columns.