Pages

Friday, May 3, 2013

Filter SharePoint list with Partial Postback to page

The other day, I wanted to filter a list view web part, triggered from a drop down list on my page. I couldn't connect to a standard out of the box filter web part because the dropdown values were populated with values retrieved from a web service. Every time I select a new value from the drop down, I wanted to automatically filter the sharepoint list with that value, without doing a full postback and refreshing the page (similar to the effect of when you filter a list from the list column options).

To start things off:
  • I created a document library and created a new column called "DocType" with a few choices:
    • Letter
    • Memo
    • Email
  • I made sure the DocType column appeared on my default view (this will be the view I use to do my filtering later)
  • I uploaded a few documents into my library, and provided the DocType for each
  • On my site page, I added the list view web part for this Document Library
  • From the AJAX Options under the list view web part settings:
    • Check off Enable Asynchronous Update
    • Show Manual Refresh Button
  • Using IE developer tools, find the element for the refresh icon with the id of ManualRefresh


Copy the outer anchor tag's onclick event (this event triggers a partial post back to the page)

  • Add a form web part to the same page
  • Grab the ID in the __doPostBack call and replace it in this script, and put the script into the form web part and save.
<div style="width:400px; height:20px; margin:0px auto; padding-bottom:20px; font-family:Verdana,Arial,Helvetica,Sans-serif;font-size:10pt;">
 Select Doc Type: 
 <select id="ddlDocType">
  <option></option>
  <option>Letter</option>
  <option>Memo</option>
 </select>
</div>


<script type='text/javascript' src='/assets/js/jquery-1.7.2.min.js'></script>
<script type="text/javascript"> 

$(document).ready(function(){
 //on the dropdown change event, call FilterMyList
 $("#ddlDocType").change(function(){
  FilterMyList();;
 });
});


function FilterMyList()
{
//get the selected value of the drop down
 var selectedDocType = $("#ddlDocType").val();
 if(selectedDocType == "" )
 { 
 //clears the filter
  __doPostBack("ctl00$m$g_95403266_84ab_485e_be73_8857b5d90f63$ctl02", "NotUTF8;__filter={DocType=" + "##dvt_all##"  + "}");
  return;
 }
 //filters the list on the selected docType
 __doPostBack("ctl00$m$g_95403266_84ab_485e_be73_8857b5d90f63$ctl02", "NotUTF8;__filter={DocType=" + selectedDocType + "}");
}  
</script>


Now, when you select a value from the dropdown, it should automatically filter the list without a full postback
 

2 comments:

  1. Is it possible to add more than one filter in the above postback function??

    ReplyDelete
  2. Hi Paras/sweet p,

    Have you found any solution to add multiple filters?If yes please help me out to solve this.

    ReplyDelete