Home > C#, MOSS 2007, SharePoint, SharePoint 2010 > SharePoint 2010: Basic List search / filter WebPart
SharePoint 2010: Basic List search / filter WebPart
April 19, 2012
jasear
Leave a comment
Go to comments
i
18 Votes


I have created a very simple SharePoint list search / filter WebPart which was inspired by the following blog post. This WebPart allows you to search records in a list where a selected field contains a specified text. It is useful in scenarios where you dont have SharePoint Search setup and just need a simple way of performing some search operations in a SharePoint List.

Adding the web part to SharePoint List View

Simply drop this web part on top of a page that contains a SharePoint View and it will allow you to apply a very simple search criteria.

The screenshot below shows the WebPart in action:

 


The field name DropDownList allows you to select from the fields that are present in the view. Once you select the field and add the text to search by, the relevant results are displayed:

 

You can also specify multiple text values by seperating the text with a semi-colon (;):

 

In the above example the specified criteria will display all the records where the manufacturer’s name contains ‘Honda’ OR ‘Audi’. The screenshot below shows the pagination working as expected:

 


Adding the web part to a page with an XsltListViewWebPart

You can also add this web part to a page that contains an XsltListViewWebPart. The web part will automatically detect that it has been added to a page (rather than a List View) and display a message asking you to select an XsltListViewWebPart that you would like to apply the filters to:

 

The screen shot below shows how to select the XsltListViewWebPart:

 

You can download the solution by clicking on the link below:

SharePoint WSP Download link

You can view the codeplex project site by clicking on the link below:

Codeplex Project Site

Please note that this is setup as a Farm Solution and not a Sandboxed Solution therefore it will not work if you deploy it to the SharePoint Solutions Gallery, you need to deploy the SharePoint Solution via Central Administration, via stsadm commands or via PowerShell commands.

How to it works

On a page that contains a ListViewWebPart you can apply filter by adding a couple of query strings:

•FilterName
•FilterMultiValue
In our example, when a user types ‘honda’ and then clicks on the search button we simply append ‘?FilterName=LinkTitle&FilterMultiValue=*honda*;’ to the query string and redirect the user to that page. Please note that ‘LinkTitle’ is the internal name of the ‘Manufacturer’ field.

The * in the *honda* is used to do a wildcard search (contains). If you would like to search for multiple texts you can seperate them by a semi-colon for example ‘FilterMultiValue=*honda*;*audi*;’ will search for records where the ‘Manufacturer’ name either contains ‘honda’ or ‘audi’. If you would like to search for an exact match rather than apply a contains filter then simply remove the *’s from the filter value text.

Although, this WebPart does not allow you to filter / search by more than one field this is very much possible. To apply filters on additional fields you simply need to append ‘FilterField1=Model&FilterValue1=Accord’ to the URL. You can apply further filters by incrementing the number i.e. FilterField2, FilterField3 …. and so on. I am not sure if there is a limit on this.

Please note that I haven’t found a way to get the wildcard search to work with this (multiple filters) approach.

Building the WebPart

In your Visual Studio solution (assuming you have created a Blank SharePoint Project) add a ‘Visual WebPart’. A Visual WebPart loads a UserControl that contains most of the code. Below is the code of the .ascx file:


view sourceprint?
01 <%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>

02 <%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

03 <%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"

04 Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

05 <%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

06 <%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>

07 <%@ Import Namespace="Microsoft.SharePoint" %>

08 <%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages"

09 Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

10 <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ListSearchUserControl.ascx.cs"

11 Inherits="Exaction.ListSearch.WebParts.ListSearch.ListSearchUserControl" %>

12 <script type="text/javascript" src="/_layouts/Exaction.ListSearch.Javascripts/jquery.min.js"></script>

13 <table>

14 <tr>

15 <td>

16 <strong>Search Criteria:</strong>

17 </td>

18 <td>

19 <asp:TextBox ID="TbSearchText" runat="server" Width="300px"></asp:TextBox>

20 </td>

21 <td>

22 &nbsp;

23 </td>

24 <td>

25 <strong>Field name:</strong>

26 </td>

27 <td>

28 <asp:DropDownList ID="DdlListFields" runat="server">

29 </asp:DropDownList>

30 </td>

31 <td>

32 &nbsp;

33 </td>

34 <td>

35 <div align="right">

36 <asp:Button ID="BtnSearch" runat="server" OnClick="BtnSearch_Click" Text="Search" />

37 <asp:Button ID="BtnClearFilter" runat="server" Visible="false" OnClick="BtnClearFilter_Click"

38 Text="Clear Criteria" />

39 </div>

40 </td>

41 </tr>

42 </table>

43 <script type="text/javascript">

44 $(document).ready(function () {

45 var base_RefreshPageTo = RefreshPageTo;

46 RefreshPageTo = function (event, url) {

47

48 var filterName = getQuerystring('FilterName');

49 var filterValue = getQuerystring('FilterMultiValue');

50 var newUrl = url + '&FilterName=' + filterName + '&FilterMultiValue=' + filterValue;

51 if (filterName != '' && filterValue != '') {

52 base_RefreshPageTo(event, newUrl);

53 }

54 else {

55 base_RefreshPageTo(event, url);

56 }

57 return;

58 }

59 });

60 function getQuerystring(key, default_) {

61 if (default_ == null) default_ = "";

62 key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

63 var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");

64 var qs = regex.exec(window.location.href);

65 if (qs == null)

66 return default_;

67 else

68 return qs[1];

69 }

70 </script>

The code above is pretty self-explanatory but very briefly it contains the UI elements (TextBox, Labels, DropDownList and Buttons) and some jQuery. The jQuery code overrides the ‘RefreshPageTo’ SharePoint javascript function. This is basically to get our filtering to work with pagination. If you have a SharePoint List View that is displaying paginated date to you then clicking on the next or previous page calls the ‘RefreshPageTo’ JavaScript function. The problem is that when this function is called it clears the querystrings we use to filter the data. To ensure that the filtering is maintained we override this function, modify the URL ensuring the filtering querystrings are present and then pass it in as the second parameter to the function.


view sourceprint?
01 using System;

02 using System.Web.UI;

03 using System.Web.UI.WebControls;

04 using System.Web.UI.WebControls.WebParts;

05 using System.Collections.Specialized;

06 using Microsoft.SharePoint;

07 using System.Collections.Generic;

08 using Exaction.ListSearch.UI.Entities;

09 using System.Text;

10

11 namespace Exaction.ListSearch.WebParts.ListSearch

12 {

13

14 /// <summary>

15 /// User control that deals with the registration process

16 /// </summary>

17 public partial class ListSearchUserControl : UserControl

18 {

19

20 /// <summary>

21 /// Gets the share point list field items.

22 /// </summary>

23 /// <param name="filterCriteria">The filter criteria.</param>

24 private List<OptionEntity> GetSharePointListFieldItems()

25 {

26 List<OptionEntity> fieldItems = new List<OptionEntity>();

27 fieldItems = new List<OptionEntity>();

28 OptionEntity item;

29 SPField field;

30 StringCollection viewFieldCollection = SPContext.Current.ViewContext.View.ViewFields.ToStringCollection();

31 foreach (string viewField in viewFieldCollection)

32 {

33 field = SPContext.Current.List.Fields.GetFieldByInternalName(viewField);

34 item = new OptionEntity();

35 item.Id = field.InternalName;

36 item.Title = field.Title;

37 fieldItems.Add(item);

38 }

39 return fieldItems;

40 }

41 protected override void CreateChildControls()

42 {

43 base.CreateChildControls();

44 List<OptionEntity> items = GetSharePointListFieldItems();

45 DdlListFields.DataSource = items;

46 DdlListFields.DataTextField = "Title";

47 DdlListFields.DataValueField = "Id";

48 DdlListFields.DataBind();

49 }

50 /// <summary>

51 /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.

52 /// </summary>

53 /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>

54 protected override void OnLoad(EventArgs e)

55 {

56 base.OnLoad(e);

57 if (!IsPostBack)

58 {

59 if (Request.QueryString["FilterName"] != null)

60 {

61 DdlListFields.SelectedValue = Request.QueryString["FilterName"].ToString();

62 }

63

64 if (Request.QueryString["FilterMultiValue"] != null)

65 {

66 TbSearchText.Text = Request.QueryString["FilterMultiValue"].ToString().Replace("*", "");

67 BtnClearFilter.Visible = true;

68 }

69 }

70 }

71 /// <summary>

72 /// Handles the Click event of the BtnSearch control.

73 /// </summary>

74 /// <param name="sender">The source of the event.</param>

75 /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>

76 protected void BtnSearch_Click(object sender, EventArgs e)

77 {

78 string redirectUrlFormat = "{0}?FilterName={1}&FilterMultiValue={2}";

79 string[] selectionCollection = TbSearchText.Text.ToString().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);

80 StringBuilder sbValues = new StringBuilder();

81 foreach (string selection in selectionCollection)

82 {

83 sbValues.Append("*" + selection.Trim() + "*;");

84 }

85

86 string urlToRedirectTo = string.Format(redirectUrlFormat, Request.Url.GetLeftPart(UriPartial.Path), DdlListFields.SelectedValue, sbValues.ToString());

87 Response.Redirect(urlToRedirectTo);

88 }

89 /// <summary>

90 /// Handles the Click event of the BtnClearFilter control.

91 /// </summary>

92 /// <param name="sender">The source of the event.</param>

93 /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>

94 protected void BtnClearFilter_Click(object sender, EventArgs e)

95 {

96 Response.Redirect(Request.Url.GetLeftPart(UriPartial.Path));

97 }

98 }

99 }

The code behind above initialises the controls and handles the Search and Clear Search Criteria Button click events.


view sourceprint?
01 using System;

02 using System.Collections.Generic;

03 using System.Linq;

04 using System.Text;

05

06 namespace Exaction.ListSearch.UI.Entities

07 {

08 public class OptionEntity

09 {

10 #region "Fields"

11 public string Id { get; set; }

12 /// <summary>

13 /// Gets or sets the title.

14 /// </summary>

15 /// <value>The title.</value>

16 public string Title { get; set; }

17 #endregion

18

19 #region "Constructor"

20 public OptionEntity()

21 {

22 }

23 #endregion

24 }

25 }

We set a collection of the OptionEntity items as the DataSource of the Field name DropDownList.

That is basically it. In this simple manner you have a WebPart that you can drop on top of any List View and apply some basic free text Filterting.

Known issues

There are two minor known issues which I haven’t found a solution for yet:

•Adding the WebPart on top of the page of a List View takes the focus away from the ListViewWebPart which in turn hides the ribbon. Once you click on the ListViewWebPart and focus on it then the ribbon becomes visible.
•This WebPart does not work properly with Views that use groupings that are collapsed by default, it works if the groupings are expanded by default
•As pointed out by Goran (see comments) it might not work with External SharePoint Lists
I hope you find this WebPart useful. Please post your comments and feedback and it would be helpful if you can rate this post.

resource:http://jasear.wordpress.com/2012/04/19/sharepoint-2010-basic-list-search-filter-webpart/

posted on 2012-11-26 17:28  ilawrence  阅读(981)  评论(0编辑  收藏  举报