I have had to try and create a Search page that displays its result set in the style of a ListViewWebPart.  This has proven quite tricky.

After a lot of Searching I found various articles on using SPQuery and then the List.RenderAsHtml(Query) to achieve this.  However I found a rather large problem with this method, whilst it queries what I want it to the resulting HTML looks nice but does not do any kind of paging also whilst the sort and filter  drop downs appear at the top of the columns, they don’t actually do any sorting or filtering.

Now that was completely unacceptable.

After a lot more searching to not much avail, I stumbled across a single line of code that told me that I could render the view as Html, not just the list.

I did some testing in a Custom aspx page to just call

SPList list = SPContext.Current.Web.Lists[“MyList”];

string s=list.DefaultView.RenderAsHtml(false, false, “Lists/MyList/Summary.aspx”);  //*

*Note that Summary is my custom view.

This worked perfectly, it displayed what I wanted and paged and filtered and sorted.

On its own this doesn’t meet all my requirements I need a complex Query to be executed based on certain Form parameters.  So the next step was to try altering the Query.

Well the View has a Query value on it so lets try that

//This line does not work
list.DefaultView.Query = <Where><Eq><FieldRef Name=’ID’ /><Value Type=’Counter’>1</Value></Eq></Where>”;

the Query property is read-only. So the next thing I tried was lets just create a new one based on the old perhaps that will allow changes.  Well it does and this bit o code will work.

SPList list = SPContext.Current.Web.Lists[“MyList”];

XmlDocument domDoc = new XmlDocument();
domDoc.LoadXml(list.DefaultView.SchemaXml);
SPView view = new SPView(list, domDoc);

view.Query = <Where><Eq><FieldRef Name=’ID’ /><Value Type=’Counter’>1</Value></Eq></Where>”;

myLabel.Text=view.RenderAsHtml(false, false, “Lists/MyList/Summary.aspx”);  // Where MyLabel is an asp Label in my Page

Now that’s done with the only hard bit is creating your CAML query on the fly based on your form values, which let’s face it isn’t that hard at all.

 

A simple Feature could be made from this, it could contain

1 custom page in _layouts (or module copied)
It has a drop down asking you to select the list you want  (created by iterating through the lists on the site).
It might also contain a dropdown to select the view you want
It contains a Large TextBox area for typing in a CAML query
A Button to “Go”

It Contains a Label to spit out the results.

This is dead simple but might be a really handy feature for messing about with CAML, you could use it to test the Query for your custom view.

 

 

Advertisements