Thursday 15 November 2012

How to add script in SharePoint web part


Add the script in webpart.cs file.     

 private const string EmbeddedScriptFormat = "<script language=\"javascript\">$(document).ready( function(){alert('hi');});</script>";

        //TESTWEBPART() is the default constructor name of the webpart class
public TESTWEBPART() { this.PreRender += new EventHandler(WebPart_ClientScript_PreRender); }

private void WebPart_ClientScript_PreRender(object sender, System.EventArgs e) { if (!Page.IsClientScriptBlockRegistered(ByeByeIncludeScriptKey)) Page.RegisterClientScriptBlock(ByeByeIncludeScriptKey, EmbeddedScriptFormat); }

ListViewByQuery control sorting,grouping,filtering,


Introduction

The ListViewByQuery control renders a list view on an application page or within a web part based on a specified query.
listviewbyquery
When the control is displayed users can sort on the columns of the list view and apply filters. But all these events need to be implemented by you otherwise the rendering will fail with an ugly error.

Syntax

The ListViewByQuery control  is part of the Microsoft.SharePoint.dll and is located in theMicrosoft.SharePoint.WebControls namespace. You can use this control declaratively when developing application pages or control templates:
<spuc:ListViewByQuery ID="CustomersListViewByQuery" runat="server" Width="700px" />
But there is a caveat: the properties List and Query only accept objects and cannot be set declaratively, only in code.
Don’t forget to add a directive at the top of the application page or control template:
<%@ Register TagPrefix="spuc" Namespace="Microsoft.SharePoint.WebControls"
             Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
If your are developing a web part you have to create the ListViewByQuery control completely in code:
private ListViewByQuery CustomersListViewByQuery;
private void EnsureChildControls()
{
     CustomersListViewByQuery = new ListViewByQuery();
     // The rest of the code follows here....
}
There are two mandatory properties that need to be set: the List property which is of type SPList and the Query property which is of type SPQuery. The OnLoad event handler or the EnsureChildControls method then contains following code:
list = SPContext.Current.Web.Lists["Customers"];
CustomersListViewByQuery.List = list;
string query = null;
if (!Page.IsPostBack)
{
    query = "<OrderBy><FieldRef Name='Title' Ascending='true' /></OrderBy>";
}
else
{
    // apply filtering and/or sorting
}
SPQuery qry = new SPQuery(list.DefaultView);
qry.Query = query;
CustomersListViewByQuery.Query = qry;
The query object must be instantiated based on an existing view of the list otherwise theListViewByQuery control will not work. The data displayed by the control is determined by the CAML query itself.
You can limit the number of rows returned by setting the RowLimit property of the SPQueryobject:
qry.RowLimit = 50;
This was the easy part but it becomes more complex when you need to implement sorting and filtering. When the user chooses to sort or to filter, the page is posted back with some extra information stored in the HttpRequest object.

Sorting

The user can decide to sort on a certain column by clicking the column header and choosing A on Top or Z on Top.
listviewbyquery-sort2
This instructs the page to post back, and the selected column and sort order is passed to the server stored into the Context.Request["SortField"]  and theContext.Request["SortDir"]. Following code sample calls the BuildSortOrder method and passes both constructs the <OrderBy> clause based on both request values.
if (!Page.IsPostBack)
{
    query = "<Query><OrderBy><FieldRef Name='Title' Ascending='true' /></OrderBy></Query>";
}
else
{
    // apply filtering and/or sorting
   if (this.Context.Request != null && this.Context.Request["SortField"] != null)
   {
       string sortorder = BuildSortOrder(this.Context.Request["SortField"],
           (this.Context.Request["SortDir"] == "Asc" ? "true" : "false"));
       if (string.IsNullOrEmpty(query))
           query = sortorder;
       else
           query += sortorder;
   }
}
Following code sample constructs the <OrderBy> clause based on both request values:
private string BuildSortOrder(string fieldName, string sortOrder)
{
    string query = null;
    if (!string.IsNullOrEmpty(fieldName))
    {
        query = string.Format("<OrderBy><FieldRef Name='{0}' Ascending='{1}' /></OrderBy>", fieldName, sortOrder);
    }           
    return query;
}

Filtering

The user can also filter the data in the ListViewByQuery control. When the different values in one of the columns is not a large set of data, the user can select from a list of distinct values.
 listviewbyquery-filter
When the page is posting back after the user action, the selected field is stored in the Context.Request["FilterField1"] and the selected value is stored in the Context.Request["FilterValue1"]. If more than 1 filter criteria is specified by the user (by selecting a value of a second column) key/value pairs are added with FilterField2 and FilterValue2 as key, and so on.
Constructing the Where clause of a CAML query is not that easy. I give you the code sample to give you an idea on how you can proceed:
private string BuildFilter()
{
    string query = "{0}";
    bool isFound = true;
    int counter = 1;
    while (isFound)
    {
          string filterfield = "FilterField" + counter.ToString();
          string filtervalue = "FilterValue" + counter.ToString();
          if (this.Context.Request[filterfield] != null && this.Context.Request[filtervalue] != null)
          {
               // Field type must be treated differently in case of other data type
               if (counter > 1)
                   query = "<And>" + query + "{0}</And>";
               query = string.Format(query, string.Format("<Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq>",
                       this.Context.Request[filterfield], this.Context.Request[filtervalue]));
               counter++;
          }
          else
          {
               isFound = false;
          }
    }
    if (!string.IsNullOrEmpty(query))
       query = "<Where>" + query + "</Where>";
    return query;
}
As one of my readers pointed out, this code snippet only works for text fields. If you want to filter on other types of fields, like number fields, choice fields or lookups, you will have to change the Type attribute from the Value element into the correct type.  To get hold on the field type, you will have to retrieve the field from the list.
SPField field = list.Fields[filterfield];
And change the query statement accordingly:
query = string.Format(query, string.Format("<Eq><FieldRef Name='{0}' /><Value Type='{1}'>{2}</Value></Eq>",
                       this.Context.Request[filterfield], field.TypeAsString, this.Context.Request[filtervalue]));

Grouping

With the ListViewByQuery control you can also build a view where the data is grouped. In that case you have to use the CAML GroupBy element:
query = "<GroupBy Collapse='FALSE'><FieldRef Name='CountryRegionName' /><FieldRef Name='City' /></GroupBy>";
This sample code groups the data by the CountryRegionName and then by City. You can specify more than one group by criterium but the choice of showing the groups collapsed or expanded must be set for all groups by using the Collapse attribute of the GroupBy element.
listviewbyquery-expanded
Use the + and - signs to expand and collapse the different groups.
If you decide to show the groups expanded, you set the Collapse attribute to TRUE and you get the following view:
listviewbyquery-collapsed
But then there is a small problem: you can expand all groups, except the latest one: it shows a Loading label but nevers shows the data.
listviewbyquery-collapsed-expanding
When taking a look at the rendered HTML you can see that all of the hyperlinks that have to do with the ListViewByQuery contain a call to the ExpCollGroup javascript call, which is a function in one of the javascript files that come with SharePoint.
Thanks to one of my readers, Alex, we can now solve this problem with a small piece of javascript. First set the Collapse attribute to FALSE and place your ListViewByQuery control in a DIV and give this DIV an ID. Immediately after the DIV  add the following javascript: 
<div id="ViewDiv" class="ms-authoringcontrols" style="width:700px">
     <spuc:ListViewByQuery ID="CustomersListViewByQuery" runat="server" Width="700px" />
</div>
<script language="javascript">
   $(document).ready( function(){
$(‘#viewDiv’).find(‘a[onclick*=ExpCollGroup]:even’).each(
function(){
this.onclick();
}
);
});
</script>   


for web part add below code to the webpart_name.cs file:

 private const string ByeByeIncludeScriptKey = "myByeByeIncludeScript";


        private const string EmbeddedScriptFormat = "<script language=\"javascript\">$(document).ready( function(){$('#ViewDiv').find('a[onclick*=ExpCollGroup]:even').each(function(){this.onclick();});});</script>";


        public TESTWEBPART()
        {
            this.PreRender += new EventHandler(WebPart_ClientScript_PreRender);
        }
        private void WebPart_ClientScript_PreRender(object sender, System.EventArgs e)
        {
            if (!Page.IsClientScriptBlockRegistered(ByeByeIncludeScriptKey))
                Page.RegisterClientScriptBlock(ByeByeIncludeScriptKey,
                EmbeddedScriptFormat);

        }

  
The ListViewByQuery control loads with all groups expanded but when it is rendered to the page, the click method is executed on all hyperlinks that have a call to  ExpCollGroup in their href attribute.