CRUD Operation in SharePoint 2013

CRUD Operation in SharePoint 2013

We can perform crud operation on SharePoint list using four object model.

To perform above operation assume you have a SharePoint list “Employee” which contains one column i.e. EmployeeName. 

1.  1. Server Side Object Model

a. Create Item
 
  1.             //Get the SP site  
  2.             using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))  
  3.             {  
  4.                 //Get the Web site  
  5.                 using (SPWeb oWeb = oSite.OpenWeb())  
  6.                 {  
  7.                     // If List not exist it will throw an error  
  8.                     SPList oList = oWeb.Lists["Employee "];  
  9.   
  10.                     //OR  
  11.   
  12.                     // If List not exist it will return null value  
  13.                     SPList oList = oWeb.Lists.TryGetList("Employee");  
  14.                     SPListItem oListItem = oList.AddItem();  
  15.                     oListItem["Title"] = "Mr";  
  16.                     oListItem["EmployeeName"] = "Arvind Kushwaha";  
  17.                     oListItem.Update();  
  18.   
  19.                 }  
  20.             }  
 
b. Update Item
 
   
  1.             //Get the SP site  
  2.             using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))  
  3.             {  
  4.                 //Get the Web site  
  5.                 using (SPWeb oWeb = oSite.OpenWeb())  
  6.                 {  
  7.                     // If List not exist it will throw an error  
  8.                     SPList oList = oWeb.Lists["Employee "];  
  9.                     //OR  
  10.                     // If List not exist it will return null value  
  11.                     SPList oList = oWeb.Lists.TryGetList("Employee");  
  12.   
  13.                     // Here you can pass dynamic ID or Your ID   
  14.                     SPListItem oListitem = oList.GetItemById(1);  
  15.                     oListitem["EmployeeName"] = "Arvind";  
  16.                     oListitem.Update();  
  17.   
  18.                 }  
  19.             }  
 
c. Delete Item
 
  1.             //Get the SP site  
  2.             using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))  
  3.             {  
  4.                 //Get the Web site  
  5.                 using (SPWeb oWeb = oSite.OpenWeb())  
  6.                 {  
  7.                     // If List not exist it will throw an error  
  8.                     SPList oList = oWeb.Lists["Employee "];  
  9.                     //OR  
  10.                     // If List not exist it will return null value  
  11.                     SPList oList = oWeb.Lists.TryGetList("Employee ");  
  12.   
  13.                     // Here you can pass dynamic ID or Your ID   
  14.                     SPListItem oListitem = oList.GetItemById(1);  
  15.                     oListitem.Delete();  
  16.   
  17.                 }  
  18.             }  
 
d. Get all Item
 
  1.            //Get the SP site  
  2.            using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))  
  3.            {  
  4.                //Get the Web site  
  5.                using (SPWeb oWeb = oSite.OpenWeb())  
  6.                {  
  7.                    // If List not exist it will throw an error  
  8.                    SPList oList = oWeb.Lists["Employee "];  
  9.                    //OR  
  10.                    // If List not exist it will return null value  
  11.                    SPList oList = oWeb.Lists.TryGetList("Employee ");  
  12.                    if (oList != null)  
  13.                    {  
  14.                        SPListItemCollection oListItemColl = oList.Items;  
  15.                        foreach (SPListItem oListItem in oListItemColl)  
  16.                        {  
  17.                            Console.WriteLine(oListItem["Title"] + "::" + oListItem["EmployeeName "]);  
  18.   
  19.                        }  
  20.                    }  
  21.                }  
  22.            }  
 
e. Get Specific Item 
 
  1.          //Get the SP site  
  2.             using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))  
  3.             {  
  4.                 //Get the Web site  
  5.                 using (SPWeb oWeb = oSite.OpenWeb())  
  6.                 {  
  7.                     // If List not exist it will throw an error  
  8.                     SPList oList = oWeb.Lists["Employee"];  
  9.                     //OR  
  10.                     // If List not exist it will return null value  
  11.                     SPList oList = oWeb.Lists.TryGetList("Employee");  
  12.   
  13.                     // Create a SPQuery Object  
  14.                     SPQuery query = new SPQuery();  
  15.   
  16.                     //Write the query (I suggest using U2U Query Bulider Tool)  
  17.                     query.Query = @"< Where >< Eq >< FieldRef Name ='EmployeeName'/>  
  18.                                     < Value Type ='Text'>Arvind </ Value ></ Eq ></ Where>";  
  19.   
  20.                     //Get the Items using Query  
  21.                     SPListItemCollection curItems = oList.GetItems(query);  
  22.                     // Go through the resulting items  
  23.                     foreach (SPListItem curItem in curItems)  
  24.                     {  
  25.                         Console.WriteLine(curItem["Title"] + "::" + curItem["EmployeeName"]);  
  26.                     }  
  27.                 }  
  28.             }  
 

2.  2. Client Side Object Model

a. Create Item
  1.             //Get the site  
  2.             string siteUrl = "SiteURL";  
  3.             ClientContext clientContext = new ClientContext(siteUrl);  
  4.             // Get the List  
  5.             List oList = clientContext.Web.Lists.GetByTitle("Employee");  
  6.             ListItemCreationInformation listCreationInformation = new ListItemCreationInformation();  
  7.             ListItem oListItem = oList.AddItem(listCreationInformation);  
  8.             oListItem["Title"] = "Mr";  
  9.             oListItem["EmployeeName"] = "Arvind Kushwaha";  
  10.             oListItem.Update();  
  11.             clientContext.ExecuteQuery();  
 
b. Update Item
 
  1.             //Get the site  
  2.             string siteUrl = "SiteURL";  
  3.             ClientContext clientContext = new ClientContext(siteUrl);  
  4.             // Get the List  
  5.             List oList = clientContext.Web.Lists.GetByTitle("Employee");  
  6.             ListItem oListItem = oList.GetItemById(1);  
  7.             oListItem["Title"] = "Male";  
  8.             oListItem.Update();  
  9.             clientContext.ExecuteQuery();  
c. Delete Item
 
  1.             //Get the site  
  2.             string siteUrl = "SiteURL”;  
  3.             ClientContext clientContext = new ClientContext(siteUrl);  
  4.             // Get the List  
  5.             List oList = clientContext.Web.Lists.GetByTitle("Employee");  
  6.             //Pass your ID  
  7.             ListItem oListItem = oList.GetItemById(1);  
  8.             oListItem.DeleteObject();  
  9.             clientContext.ExecuteQuery();  
 
d. Get all Item
 
  1. //Get the site  
  2.            string siteUrl = "SiteURL";  
  3.            ClientContext clientContext = new ClientContext(siteUrl);  
  4.            // Get the List  
  5.            List oList = clientContext.Web.Lists.GetByTitle("Employee");  
  6.            CamlQuery query = new CamlQuery();  
  7.            query.ViewXml = "<View/>";  
  8.            ListItemCollection items = oList.GetItems(query);  
  9.            clientContext.Load(oList);  
  10.            clientContext.Load(items);  
  11.            clientContext.ExecuteQuery();  
 
e. Get Specific Item
 
  1. //Get the site  
  2.             string siteUrl = "SiteURL";  
  3.             ClientContext clientContext = new ClientContext(siteUrl);  
  4.             // Get the List  
  5.             List oList = clientContext.Web.Lists.GetByTitle("Employee");  
  6.             CamlQuery query = new CamlQuery();  
  7.             query.ViewXml = @"<View>  
  8.                                 <Query>  
  9.                                     <Where>  
  10.                                         <Eq>  
  11.                                             <FieldRef Name='EmployeeName '/>  
  12.                                             <Value Type='Text'>Arvind Kushwaha</Value>  
  13.                                         </Eq>  
  14.                                     </Where>  
  15.                                 </Query>  
  16.                              </View>";  
  17.             ListItemCollection listItems = oList.GetItems(query);  
  18.             clientContext.Load(listItems, items => items.Include(  
  19.                                                             item => item["Id"],  
  20.                                                             item => item["Title"],  
  21.                                                             item => item["EmployeeName"]  
  22.                                                             ));  
  23.             clientContext.ExecuteQuery();  
 

3.  3. JavaScript Object Model

a. Create Item
 
  1. //Get the site  
  2.    var contex = new SP.ClientContext("Your Site URL");  
  3.   
  4.    //Get the web  
  5.    var web = contex.get_web();  
  6.   
  7.    //Get the List based upon the Title   
  8.    var list = web.get_lists().getByTitle("Employee");  
  9.   
  10.    //Object for creating Item in the List     
  11.    var listItem = list.addItem(listCreationInformation);  
  12.    listItem.set_item("Title""MR");  
  13.    listItem.set_item("EmployeeName""Arvind Kushwaha");  
  14.   
  15.    //Update the List Item  
  16.    listItem.update();  
  17.    ctx.load(listItem);  
  18.    //Execute the batch Asynchronously  
  19.    ctx.executeQueryAsync(Function.createDelegate(this, success), Function.createDelegate(this, fail));  

The above code perform the following operations.

  •  To add a new item in the list, the SP.ListCreationInformation() object is used
  •  This object is then passed to the addItem() method of the List. This method returns the ListItem object
  •  Using the set_item() method of the ListItem the values for each field in the List is set and finally the list is updated.
 
b. Update Item
  1. //Get the site  
  2.     var contex = new SP.ClientContext("Your Site URL");  
  3.   
  4.     //Get the web  
  5.     var web = contex.get_web();  
  6.   
  7.     //Get the List based upon the Title   
  8.     var list = web.get_lists().getByTitle("Employee");  
  9.     ctx.load(list);  
  10.     listItem = list.getItemById(1);  
  11.     ctx.load(listItem);  
  12.     listItem.set_item("EmployeeName""Arvind Kushwaha");  
  13.     listItem.update();  
  14.     ctx.executeQueryAsync(Function.createDelegate(this, success), Function.createDelegate(this, fail));  
 The above code perform the Update the ListItem based upon the id:
 
c. Delete Item
  1. //Get the site  
  2.     var contex = new SP.ClientContext("Your Site URL");  
  3.   
  4.     //Get the web  
  5.     var web = contex.get_web();  
  6.   
  7.     //Get the List based upon the Title   
  8.     var list = web.get_lists().getByTitle("Employee");  
  9.     ctx.load(list);  
  10.     listItem = list.getItemById(1);  
  11.     ctx.load(listItem);  
  12.     listItem.deleteObject();  
  13.     ctx.executeQueryAsync(Function.createDelegate(this, success), Function.createDelegate(this, fail));  
 The above code perform the Delete the ListItem based upon the id
 
d. Get all Item
 
  1. //Get the site  
  2.    var contex = new SP.ClientContext("Your Site URL");  
  3.   
  4.    //Get the web  
  5.    var web = contex.get_web();  
  6.   
  7.    //Get the List based upon the Title   
  8.    var list = web.get_lists().getByTitle("Employee");  
  9.   
  10.    //The Query object. This is used to query for data in the List  
  11.    var query = new SP.CamlQuery(); ctx.load(list);  
  12.    query.set_viewXml('<View></View>');  
  13.    var items = list.getItems(query);  
  14.   
  15.    //Retrieves the properties of a client object from the server.  
  16.    ctx.load(list);  
  17.    ctx.load(items);  
  18.    ctx.executeQueryAsync(  
  19.     Function.createDelegate(thisfunction () {  
  20.   
  21.         var enumerator = items.getEnumerator();  
  22.         while (enumerator.moveNext()) {  
  23.             var currentListItem = enumerator.get_current();  
  24.             alert(currentListItem.get_item("ID"));  
  25.             alert(currentListItem.get_item("Title"));  
  26.             alert(currentListItem.get_item("EmployeeName"));  
  27.         }  
  28.     }),  
  29.    Function.createDelegate(this, fail)  
  30.  );  

The above code performs the following operations:

 

  • Use SP.CamlQuery() to create query object for querying the List
  • The query object is set with the criteria using xml expression using set_viewXml() method
  • Using getItems() method of the List the query will be processed
  • executeQueryAsync() methods processes the batch on the server and retrieve the List data. This data is displayed using HTML table after performing iterations on the retrieved data

 

e. Get Specific Item
  1. //Get the site  
  2.     var contex = new SP.ClientContext("Your Site URL");  
  3.   
  4.     //Get the web  
  5.     var web = contex.get_web();  
  6.   
  7.     //Get the List based upon the Title   
  8.     var list = web.get_lists().getByTitle("Employee");  
  9.   
  10.     //The Query object. This is used to query for data in the List  
  11.     var query = new SP.CamlQuery(); ctx.load(list);  
  12.     //Create the CAML that will return only items with the titles that begin with 'A'    
  13.     query.set_viewXml('<View><Query><Where><BeginsWith><FieldRef Name="EmployeeName" /><Value Type="Text">A</Value></BeginsWith></Where></Query></View>');  
  14.     var items = list.getItems(query);  
  15.   
  16.     //Retrieves the properties of a client object from the server.  
  17.     ctx.load(list);  
  18.     ctx.load(items);  
  19.     ctx.executeQueryAsync(  
  20.   
  21.    Function.createDelegate(thisfunction () {  
  22.   
  23.        //Get an enumerator for the items in the list    
  24.        var enumerator = items.getEnumerator();  
  25.        while (enumerator.moveNext()) {  
  26.            var currentListItem = enumerator.get_current();  
  27.            alert(currentListItem.get_item("ID"));  
  28.            alert(currentListItem.get_item("Title"));  
  29.            alert(currentListItem.get_item("EmployeeName"));  
  30.        }  
  31.    }),  
  32.     Function.createDelegate(this, fail)  
  33.     );  

The above code performs the following operations:

  • Use SP.CamlQuery() to create query object for querying the List
  • The query object is set with the criteria using xml expression using set_viewXml() method
  • Using getItems() method of the List the query will be processed
  • executeQueryAsync() methods processes the batch on the server and retrieve the List data. This data is displayed using HTML table after performing iterations on the retrieved data 

4.  4. REST-API Object Model.

a. Create Item
 
  1. // Declare the variable.  
  2.    var listname="Employee",  
  3.        url=_spPageContextInfo.webAbsoluteUrl;  
  4.    // Preparing our update  
  5.    var item = $.extend({  
  6.        "__metadata": { "type": getListItemType(listname)}  
  7.    }, metadata);  
  8.    item.Title="MR";  
  9.    item.EmployeeName="Arvind Kushwaha""  
  10.      
  11.    // Executing our adding operation  
  12.    $.ajax({  
  13.        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",  
  14.        type: "POST",  
  15.        contentType: "application/json;odata=verbose",  
  16.        data: JSON.stringify(item),  
  17.        headers: {  
  18.            "Accept""application/json;odata=verbose",  
  19.            "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  20.            "Content-Type":"application/json;odata=verbose",  
  21.            "X-HTTP-Method""POST"  
  22.        },  
  23.        success: function (data) {  
  24.            success(data); // Returns the newly created list item information  
  25.        },  
  26.        error: function (data) {  
  27.            failure(data);  
  28.        }  
  29.    });  
 
b. Update Item
  1. // Declare the variable.  
  2.     var listname="Employee",  
  3.            id=1,  
  4.         url=_spPageContextInfo.webAbsoluteUrl;  
  5.     var item = $.extend({  
  6.         "__metadata": { "type": getListItemType(listname)}  
  7.     }, metadata);  
  8.     item.EmployeeName=’Arvind’;  
  9.       
  10.     // Executing our Update operation based on ID  
  11.     $.ajax({  
  12.         url: url + "/_api/web/lists/getbytitle('" + listname + "')/items(id)",  
  13.         type: "POST",  
  14.         contentType: "application/json;odata=verbose",  
  15.         data: JSON.stringify(item),  
  16.         headers: {  
  17.             "Accept""application/json;odata=verbose",  
  18.             "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  19.             "Content-Type":"application/json;odata=verbose",  
  20.             "X-HTTP-Method""MERGE"  
  21.         },  
  22.         success: function (data) {  
  23.             success(data); // Returns the newly created list item information  
  24.         },  
  25.         error: function (data) {  
  26.             failure(data);  
  27.         }  
  28.     });  
 
c. Delete Item
  1. // Declare the variable.  
  2.     var listname="Employee",  
  3.            id=1,  
  4.         url=_spPageContextInfo.webAbsoluteUrl;  
  5.   
  6.     // Executing our delete operation based on ID  
  7.     $.ajax({  
  8.         url: url + "/_api/web/lists/getbytitle('" + listname + "')/items(id)",  
  9.         type: "POST",  
  10.         contentType: "application/json;odata=verbose",  
  11.         headers: {  
  12.             "Accept""application/json;odata=verbose",  
  13.             "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
  14.             "Content-Type":"application/json;odata=verbose",  
  15.             "X-HTTP-Method""DELETE"  
  16.         },  
  17.         success: function (data) {  
  18.             success(data); // Returns the newly created list item information  
  19.         },  
  20.         error: function (data) {  
  21.             failure(data);  
  22.         }  
  23.     });  
 
d. Get all Item
 
  1. // Declare the variable.  
  2.     var url = _spPageContextInfo.webAbsoluteUrl;  
  3.     listname="Employee";  
  4.   
  5.     // Retrieve all the item   
  6.     $.ajax({  
  7.         url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",  
  8.         method: "GET",  
  9.         headers: { "Accept""application/json; odata=verbose" },  
  10.         success: function (data) {  
  11.             // Returning the results  
  12.             console.log(data.d.results);  
  13.         },  
  14.         error: function (data) {  
  15.             failure(data);  
  16.         }  
  17.     });  
 
e. Get Specific Item
 
  1.  // Declare the variable  
  2.     var url = _spPageContextInfo.webAbsoluteUrl;  
  3.   
  4.     // Retrieve the item Title and Employee Name  
  5.     $.ajax({  
  6.         url: url + "/_api/web/lists/getbytitle('listname')/Items/?$select=Title,EmployeeName",  
  7.     method: "GET",  
  8.     headers: { "Accept""application/json; odata=verbose" },  
  9.     success: function (data) {  
  10.         // Returning the results  
  11.         console.log(data.d.results);  
  12.     },  
  13.     error: function (data) {  
  14.         failure(data);  
  15.     }  
  16. });  
  

Note:

$select: Which column to retrieve in result.

$filter: What should be retrieve in result.

$expand: Retrieve the lookup column in result
 
Ebook Download
View all
Learn
View all