Search This Blog

Monday, March 2, 2015

Cascading Drop-Down List in SharePoint 2010 List Using jQuery

Introduction

This article explains how to implement a Cascading Drop-Down List in a SharePoint 2010 List using jQuery and Sp services.

To implement a Cascading Drop-Down List in a SharePoint 2010 List using jQuery and Sp services use the following procedure.

Object
  1. Create a Country custom list:

    Country List
     
  2. Create a State Custom list: with a Country lookup column:

    State Column List

    Look up Column Settings:

    State List

    State List
     
  3. Create a CascadeDropDownList with Country and State lookup columns.
     
  4. Select the Default New Form under the List tab of the newly created List CascadeDropDownList. 

    Default New Form
     
  5. Add a Content Editor Web part and select Edit HTML Source under the Format Text Tab.

    HTML Source in Form
     
  6. Copy and Paste the following code in the HTML Editor: 
    1. <script language="javascript" src="/JSLibrary/jquery-1.4.2.min.js" type="text/javascript">  
    2. </script> <script language="javascript" src="/JSLibrary/jquery.SPServices-0.5.7.min.js" type="text/javascript"></script>  
    3. <script type="text/javascript">  
    4.    
    5.   $(document).ready(function() {  
    6.    
    7.             $().SPServices.SPCascadeDropdowns({  
    8.    
    9.                 relationshipList: "State",  
    10.    
    11.                 relationshipListParentColumn: "Country",  
    12.    
    13.                 relationshipListChildColumn: "Title",  
    14.    
    15.                 relationshipListSortColumn: "ID",  
    16.    
    17.                 parentColumn: "Country",  
    18.    
    19.                 childColumn: "State",  
    20.    
    21.                 promptText: "Choose State...",  
    22.    
    23.                 debug: true  
    24.    
    25.             });  
    26.    
    27. });  
    28. </script>  
            Cascade Drop DownList
Summary
In some scenario we need to implement a cascading type of concept in OOB forms as for example by selecting a Country's respective states or cities. It's not easier in SharePoint.

Visual webpart in SharePoint 2013 using Visual studio 2012

Building Visual webpart:

Open visual studio 2012, click on new project select SharePoint solutions under the office/SharePoint from which select project type as SharePoint 2013- Visual web Part.
Enter your project name, here it is First-VisualWebPart.


Click OK. It will open the wizard to create the project.
Select the site where you want to deploy the webpart.  "http://dvlabapp01".
Click on Validate Option to validate the site details. It will show the pop-up saying that connection successful.


Close the Pop-up, and select Deploy as a sandbox solution and click on Finish to create the project for this webpart.


You can see the below screenshot which represents the project structure for the webpart.

In this article we will take a simple example of getting the data from the list and bind it to the dropdown control using the SharePoint object model.
I am adding one dropdown "ddltickets" and button "btngettickets" controls to the page. Whenever a user clicks on the button, it will load all the ticket details in the system. To design the page write the below lines of code in your

Visual webpart.ascx file:

1234567891011121314151617181920212223
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="VisualWebPart1.ascx.cs" Inherits="First_VisualWebPart.VisualWebPart1.VisualWebPart1" %>
<table >
<tr>
<td>
<asp:DropDownList ID="ddltickets" runat="server"></asp:DropDownList>
</td>
<td>
 
</td>
<td>
<asp:Button ID="btngettickets" runat="server" Text="Get Ticket Information" OnClick="btngettickets_Click" />
</td>
 
</tr>
 
</table>
view rawwebpart.ascx hosted with ❤ by GitHub
Add Microsoft.SharePoint.dll to the project to write the code in the SharePoint object Model which requires  Microsoft.SharePoint namespace.

After adding the dll reference write the below code in

Visual webpart.cs file:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
using System;
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using Microsoft.SharePoint;
namespace First_VisualWebPart.VisualWebPart1
{
[ToolboxItemAttribute(false)]
public partial class VisualWebPart1 : WebPart
{
// Uncomment the following SecurityPermission attribute only when doing Performance Profiling using
// the Instrumentation method, and then remove the SecurityPermission attribute when the code is ready
// for production. Because the SecurityPermission attribute bypasses the security check for callers of
// your constructor, it's not recommended for production purposes.
// [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
public VisualWebPart1()
{
}
 
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeControl();
}
 
protected void Page_Load(object sender, EventArgs e)
{
}
 
protected void btngettickets_Click(object sender, EventArgs e)
{
DataTable dt = GetItemDetails();
ddltickets.DataSource = dt;
ddltickets.DataTextField = "Title";
ddltickets.DataValueField = "Title";
ddltickets.DataBind();
}
 
private DataTable GetItemDetails()
{
SPWeb spweb = SPContext.Current.Web;
SPList ticketsList = spweb.GetList("http://dvlabapp01.cloudapp.net/Lists/Ticket%20Details/AllItems.aspx");
 
return ticketsList.Items.GetDataTable();
}
}
}
view rawwebpart.cs hosted with ❤ by GitHub
Once you have added the code, its time for

Deploying webpart:

To deploy the webpart, right click on the project and click on deploy. During deployment, in the output window you can observe all the steps that are happening for the first time, see the below screenshot.
Some of the important steps are
  1. Configuring the Sandbox code service
  2. Adding solution
  3. Deploying solution
  4. Activate Features

Once the webpart have been successfully deployed then you can 

Add the webpart to the page:

To add the webpart which we have deployed, Open the page and click on the edit page option. From the INSERT tab, select webpart icon. Choose the webpart deployed from custom category, select the web part that needs to be added to the page and click on Add button.

After adding the webpart, whenever a user clicks on the "Get ticket Information" button the dropdown list control populates the required information.

Redeploying webpart:

If you make any changes to webpart and wanted to deploy again. Follow the same step, right click on the project and click deploy option. But this time if you observe the Output window some of the new steps in redeployment you can observe in below screenshot.
  1. Retract solution
  2. Deactivating feature
  3. Deleting the solution
Once the above steps got completed, It will perform below steps
  1. Add Solution
  2. Deploying solution
  3. Activate Features
- See more at: http://www.sharepoint-journey.com/visual-webpart-in-sharepoint-2013.html#sthash.OSE6DiRE.dpuf

Creating List Programatically in SharePoint 2010 using Visual Studio 2010


Today we will discuss about creating List programmatically in SharePoint 2010 usingVisual studio 2010.
If we are using only one instance of list we will follow this approach for creating list.
open the visual studio 2010.
File-->New-->Project
Select C#-->SharePoint-->2010
Select Empty SharePoint Project




Deploy as a Form solution.
Click on Finish



Project Solution structure is below for Empty SharePoint Project.



Select the project and click on F4 for the properties.
Check for the Sandbox Solution property it is set to false now as we select the Trust level for SharePoint solution as From Solution.
From here if you change that to Sandbox solution by setting property
Sandbox Solution=”True”
You can edit the site URL which you want to deploy using site URL property.





Right Click on Feature node and click on AddFeature.



It will add Feature1 to the Features node in the project.
Change the Title according to your requirement .Here it is Devendra Employee List feature.
I want this List available at site collection level to achieve this we need to change the
Scope From Web to Site.



Now I am using Scope as web level only.



We will create a list using object model because we are going to use only one instance of this list so there is no point of creating list definition.
To do that I will add a feature receiver.
Add Event Receiver to the Feature1 node in the project.



Go ahead and add . Then uncomment the FeatureActivated event .
We will write a code here which will add the Employee List whenever we activated this feature.

using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;

namespace Devendra_Feature_Event_Receivers.Features.AddList
{
 /// 
 /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
 /// 
 /// 
 /// The GUID attached to this class may be used during packaging and should not be modified.
 /// 

 [Guid("5bf5f6c5-c371-419a-984b-f0ecf9ddeda0")]
 public class Feature1EventReceiver : SPFeatureReceiver
 {
     // Uncomment the method below to handle the event raised after a feature has been activated.
     public override void FeatureActivated(SPFeatureReceiverProperties properties)
     {
         try
         {
             //get the current web object.
             SPWeb web = properties.Feature.Parent as SPWeb;

          
             SPList list = web.EnsureList("Employee", "This list contains Employee details.", SPListTemplateType.GenericList);

         
             if (list != null)
             {
              
                 SPField field = list.EnsureField("Title", "", SPFieldType.Text, true);
                 field.Title = "FirstName";
                 field.Update();

              
                 SPField fld = null;
             
                 fld = list.EnsureField("LastName", "Employee LastName", SPFieldType.Text, true);

              
                 if (fld != null)
                 {
                     SPView view = list.Views[0];
                     view.ViewFields.Add(fld);
                     view.Update();
                     fld = null;
                 }
              
                 SPListItemCollection listItems = list.Items;
                 AddItems(listItems, "Devendra", "Velegandla");
             }
             else
             {

             }
         }
         catch (Exception ex)
         {
             throw ex;
         }
     }
     public static void AddItems(SPListItemCollection listItems, string FirstName, string LastName)
     {
         SPListItem item = null;
         item = listItems.Add();
         item["FirstName"] = FirstName;
         item["LastName"] = LastName;
         item.Update();
     }

     public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
     {
     
         SPWeb web = properties.Feature.Parent as SPWeb;
   
         web.DeleteList("Employee");
     }



 }

}


add one more class called utilities.cs of type static.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace Devendra_Feature_Event_Receivers.Features.AddList
{
 public static class Utilities
 {

     public static SPList EnsureList(this SPWeb web, string listTitle, string desc, SPListTemplateType lstTemplateType)
     {
     
         SPListCollection lstCollection = web.Lists;

    
         SPList lstObj = (from SPList lst in lstCollection
                          where string.Equals(lst.Title, listTitle, StringComparison.InvariantCultureIgnoreCase) == true
                          select lst).FirstOrDefault();

     
         if (lstObj != null)
         {
             return lstObj;
         }
     
         Guid lstGuid = web.Lists.Add(listTitle, desc, lstTemplateType);
         try
         {
             SPList newList = web.Lists.GetList(lstGuid, true);
             newList.OnQuickLaunch = true;
             newList.Update();
             return newList;
         }
         catch
         {
             return null;
         }
     }
 
     public static SPField EnsureField(this SPList list, string fldDisplayName, string fldDesc, SPFieldType fldType, bool isMadatory)
     {
     
         SPFieldCollection fieldCollection = list.Fields;

     
         SPField spField = (from SPField field in fieldCollection
                            where string.Equals(field.Title, fldDisplayName, StringComparison.InvariantCultureIgnoreCase) == true
                            select field).FirstOrDefault();

     
         if (spField != null)
         {
             return spField;
         }
      
         try
         {
             list.Fields.Add(fldDisplayName, fldType, isMadatory);
             SPField spfield = list.Fields.GetField(fldDisplayName);
             spfield.Description = fldDesc;
             spfield.Update();
             return spfield;
         }
         catch
         {
             return null;
         }
     }
 
     public static bool DeleteList(this SPWeb web, string listTitle)
     {
      
         SPListCollection lstCollection = web.Lists;

      
         SPList lstObj = (from SPList lst in lstCollection
                          where
                              string.Equals(lst.Title, listTitle, StringComparison.InvariantCultureIgnoreCase) == true
                          select lst).FirstOrDefault();

      
         if (lstObj != null)
         {
             try
             {
                 lstObj.Delete();
                 return true;
             }
             catch (Exception ex)
             {
             }
         }
         return false;
     }
 }
}




Add Item to the list data to the Employee List.
Once we deactivate this feature the list will get deleted.
Add one more class call utilities.



Once you click on the package .go to Bin folder of the project get the WSP file.



Add the solution using stsadm command.
Click on run: type CMD
Execute below command
Stsadm –o addsolution –filename c:\Devendra_Feature_Event_Receiver.wsp.

Open Central Admin to deploy the solution.
Got o system settings -> Manage Form solutions



Deploy the solution.
You can see the below screen solution deployed globally.



Open the site URL which we deployed the solution.
Click on SiteActions-->Site settings
Under Site Actions click on Manage Site Features.




Activate the feature Devendra Employee List Feature.



After activation we can see the Employee list and data inserted into the list.



Once you deactivate the feature list will get deleted.

Some Code For Grid View and Model Popup in Javascript

DataGrid/ListBox Paging in Silverlight 4

Xaml Code:-
open tag data:datapager name="Datapager1" pagesize="10" displaymode="FirstLastPreviousNext" autoellipsis="True" horizontalalignment="Left" numericbuttoncount="3" istotalitemcountfixed="True/">



Code Behind: 


using System.Window.Data;
PagedCollectionView pagedcollectionview = new PagedCollectionView(“Collection”));
Datapager1.Source= pagedcollectionview;
myDatagrid.ItemsSource = pagedcollectionview;


Modal Window using javascript
To open Modal Dialog Box/Window
Step 1.open script tag
function onClientClick(){
var Options=SP.UI.$Create.Dialogoptions();
Options.Url="url";
Options.Width=500;
Options.Height=200;
SP.UI.ModalDialog.ShowModalDialog(Options);
return false;
}
close script tag
Step 2. To Call javascript function
open anchor(a) tag href="javascript:void(0);" id ="view" onclick="onClientClick"
View All
close anchor tag


GridView

Bind Gridview with Sharepoint list data
Step 1. Create ASPX page, and add following code
asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
asp:GridView
AutoGenerateColumns is false

Step 2. Add reference:- Microsoft.Sharepoint

Step 3.Add following code into ASPX.cs file
Using Microsoft.Sharepoint;

SPSite oSite= new SPSite("SiteUrl");
SPWeb oWeb;
SPList oList;
DataTable dt;

Page_Load()
{
if(!Page.IsPostBack)
{
FetchData();
}
}

Protected void FetchData()
{
oWeb=oSite.OpenWeb();
oList=oWeb.Lists["ListName"];
SPListItemCollection oListCol;
oListCol=oList.Items;
dt=new DataTable ();
dt.Columns.Add("Title",typeof(string));
dt.Columns.Add("Created",typeof(DateTime));
DataRow dr;
foreach(SPListItem oListItem in oListCol)
{
dr=dt.Rows.Add();
dr["Title"]=oListItem["Title"].tostring();
}

gridview1.Datasource=dt;
gridview1.DataBind();
}

Create Sharepoint 2010 List Programmatically with custom fields


Code Behind:-

SPSite _site;
SPWeb _myWeb;
bool gTemplateExists = false;
string _strList = "ListName";
_site = new SPSite(@"SiteUrl");
_myWeb = _site.OpenWeb();
//check Whether list already exist or not.
if (IsListExists(_myWeb, _strList) == false)
{
CreateNewList(_strList);
}

public bool IsListExists(SPWeb pWeb, string pListName)
{
try
{
SPList list = pWeb.Lists[pListName];
if (list == null)
return false;
else
return true;
}
catch (Exception ex)
{
return false;
}
}

public void CreateNewList(string pListName)
{
try
{
_myWeb.AllowUnsafeUpdates = true;
SPListCollection lists = _myWeb.Lists;

// create new Generic list called ListName
lists.Add("ListName", "List Description", SPListTemplateType.GenericList);
SPList list = _myWeb.Lists["ListName"];
// create Text type new column called "Title"
SPFieldText fldTitle = (SPFieldText)list.Fields.CreateNewField(
SPFieldType.Text.ToString(), " Title ");
fldTitle.Required = false;
// create DateTime type new column called "DateTime"
SPFieldDateTime fldDateTime = (SPFieldDateTime)list.Fields.CreateNewField(
SPFieldType.DateTime.ToString(), "DateTime");
fldDateTime.DisplayFormat = SPDateTimeFieldFormatType.DateTime;

/* add the new fields to the list */
list.Fields.Add(fldTitle);
list.Fields.Add(fldDateTime);

/* finally update list */
list.Update();

/*add the new fields to view */
SPView view = list.DefaultView;
view.ViewFields.Add("Title");
view.ViewFields.Add("DateTime");
view.Update();

_myWeb.AllowUnsafeUpdates = false;
}
catch (Exception ex)
{
}

}

Method to get Current logged In user using Client object model


In this article, I will show method used to get current logged In user using client object model.

private User GetCurrentLoggedInUser()
{
Web oWebSite = ClientContext.Current.Web;
ClientContext.Current.Load(oWebSite);
ClientContext.Current.ExecuteQuery();

User oUser = oWebSite.CurrentUser;
ClientContext.Current.Load(oUser);
ClientContext.Current.ExecuteQuery();
return oUser;
}
This method return User object. so to get loggedIn user create User class object and call this method.
Private User oUser = GetCurrentLoggedInUser ();

Programmatically create custom default page for SharePoint 2010 Team site


In this article, I will explain how to programmatically create custom default page and set it to root level.
Step 1. Select SharePoint empty project template and then add Module.
Step 2.Update the elements manifest to tell where to find the custom file /Page and where it needs to deploy.

. ?xml version="1.0" encoding="utf-8"?>
Elements xmlns="http://schemas.microsoft.com/sharepoint/">
Module Name="Home" Url="" Path="">. ?xml version="1.0" encoding="utf-8"?>
Elements xmlns="http://schemas.microsoft.com/sharepoint/">
Module Name="Home" Url="" Path="">
File Path="Home\default.aspx" Url="default.aspx" IgnoreIfAlreadyExists="TRUE" Type="Ghostable">
/File>
/Module>
/Elements>


Step 3. Add event handler to the feature.
SPWeb oWeb = null;
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
oWeb = (SPWeb)properties.Feature.Parent;
SPFolder rootfolder = oWeb.RootFolder;
rootfolder.WelcomePage = "default.aspx";
rootfolder.Update();
}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
oWeb = (SPWeb)properties.Feature.Parent;
SPFolder rootfolder = oWeb.RootFolder;
rootfolder.WelcomePage = "SitePages/Home.aspx";
rootfolder.Update();
}