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
-
- using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))
- {
-
- using (SPWeb oWeb = oSite.OpenWeb())
- {
-
- SPList oList = oWeb.Lists["Employee "];
-
-
-
-
- SPList oList = oWeb.Lists.TryGetList("Employee");
- SPListItem oListItem = oList.AddItem();
- oListItem["Title"] = "Mr";
- oListItem["EmployeeName"] = "Arvind Kushwaha";
- oListItem.Update();
-
- }
- }
b. Update Item
-
- using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))
- {
-
- using (SPWeb oWeb = oSite.OpenWeb())
- {
-
- SPList oList = oWeb.Lists["Employee "];
-
-
- SPList oList = oWeb.Lists.TryGetList("Employee");
-
-
- SPListItem oListitem = oList.GetItemById(1);
- oListitem["EmployeeName"] = "Arvind";
- oListitem.Update();
-
- }
- }
c. Delete Item
-
- using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))
- {
-
- using (SPWeb oWeb = oSite.OpenWeb())
- {
-
- SPList oList = oWeb.Lists["Employee "];
-
-
- SPList oList = oWeb.Lists.TryGetList("Employee ");
-
-
- SPListItem oListitem = oList.GetItemById(1);
- oListitem.Delete();
-
- }
- }
d. Get all Item
-
- using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))
- {
-
- using (SPWeb oWeb = oSite.OpenWeb())
- {
-
- SPList oList = oWeb.Lists["Employee "];
-
-
- SPList oList = oWeb.Lists.TryGetList("Employee ");
- if (oList != null)
- {
- SPListItemCollection oListItemColl = oList.Items;
- foreach (SPListItem oListItem in oListItemColl)
- {
- Console.WriteLine(oListItem["Title"] + "::" + oListItem["EmployeeName "]);
-
- }
- }
- }
- }
e. Get Specific Item
-
- using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))
- {
-
- using (SPWeb oWeb = oSite.OpenWeb())
- {
-
- SPList oList = oWeb.Lists["Employee"];
-
-
- SPList oList = oWeb.Lists.TryGetList("Employee");
-
-
- SPQuery query = new SPQuery();
-
-
- query.Query = @"< Where >< Eq >< FieldRef Name ='EmployeeName'/>
- < Value Type ='Text'>Arvind </ Value ></ Eq ></ Where>";
-
-
- SPListItemCollection curItems = oList.GetItems(query);
-
- foreach (SPListItem curItem in curItems)
- {
- Console.WriteLine(curItem["Title"] + "::" + curItem["EmployeeName"]);
- }
- }
- }
2. 2. Client Side Object Model
a. Create Item
-
- string siteUrl = "SiteURL";
- ClientContext clientContext = new ClientContext(siteUrl);
-
- List oList = clientContext.Web.Lists.GetByTitle("Employee");
- ListItemCreationInformation listCreationInformation = new ListItemCreationInformation();
- ListItem oListItem = oList.AddItem(listCreationInformation);
- oListItem["Title"] = "Mr";
- oListItem["EmployeeName"] = "Arvind Kushwaha";
- oListItem.Update();
- clientContext.ExecuteQuery();
b. Update Item
-
- string siteUrl = "SiteURL";
- ClientContext clientContext = new ClientContext(siteUrl);
-
- List oList = clientContext.Web.Lists.GetByTitle("Employee");
- ListItem oListItem = oList.GetItemById(1);
- oListItem["Title"] = "Male";
- oListItem.Update();
- clientContext.ExecuteQuery();
c. Delete Item
-
- string siteUrl = "SiteURL”;
- ClientContext clientContext = new ClientContext(siteUrl);
-
- List oList = clientContext.Web.Lists.GetByTitle("Employee");
-
- ListItem oListItem = oList.GetItemById(1);
- oListItem.DeleteObject();
- clientContext.ExecuteQuery();
d. Get all Item
-
- string siteUrl = "SiteURL";
- ClientContext clientContext = new ClientContext(siteUrl);
-
- List oList = clientContext.Web.Lists.GetByTitle("Employee");
- CamlQuery query = new CamlQuery();
- query.ViewXml = "<View/>";
- ListItemCollection items = oList.GetItems(query);
- clientContext.Load(oList);
- clientContext.Load(items);
- clientContext.ExecuteQuery();
e. Get Specific Item
-
- string siteUrl = "SiteURL";
- ClientContext clientContext = new ClientContext(siteUrl);
-
- List oList = clientContext.Web.Lists.GetByTitle("Employee");
- CamlQuery query = new CamlQuery();
- query.ViewXml = @"<View>
- <Query>
- <Where>
- <Eq>
- <FieldRef Name='EmployeeName '/>
- <Value Type='Text'>Arvind Kushwaha</Value>
- </Eq>
- </Where>
- </Query>
- </View>";
- ListItemCollection listItems = oList.GetItems(query);
- clientContext.Load(listItems, items => items.Include(
- item => item["Id"],
- item => item["Title"],
- item => item["EmployeeName"]
- ));
- clientContext.ExecuteQuery();
3. 3. JavaScript Object Model
a. Create Item
-
- var contex = new SP.ClientContext("Your Site URL");
-
-
- var web = contex.get_web();
-
-
- var list = web.get_lists().getByTitle("Employee");
-
-
- var listItem = list.addItem(listCreationInformation);
- listItem.set_item("Title", "MR");
- listItem.set_item("EmployeeName", "Arvind Kushwaha");
-
-
- listItem.update();
- ctx.load(listItem);
-
- 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
-
- var contex = new SP.ClientContext("Your Site URL");
-
-
- var web = contex.get_web();
-
-
- var list = web.get_lists().getByTitle("Employee");
- ctx.load(list);
- listItem = list.getItemById(1);
- ctx.load(listItem);
- listItem.set_item("EmployeeName", "Arvind Kushwaha");
- listItem.update();
- 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
-
- var contex = new SP.ClientContext("Your Site URL");
-
-
- var web = contex.get_web();
-
-
- var list = web.get_lists().getByTitle("Employee");
- ctx.load(list);
- listItem = list.getItemById(1);
- ctx.load(listItem);
- listItem.deleteObject();
- 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
-
- var contex = new SP.ClientContext("Your Site URL");
-
-
- var web = contex.get_web();
-
-
- var list = web.get_lists().getByTitle("Employee");
-
-
- var query = new SP.CamlQuery(); ctx.load(list);
- query.set_viewXml('<View></View>');
- var items = list.getItems(query);
-
-
- ctx.load(list);
- ctx.load(items);
- ctx.executeQueryAsync(
- Function.createDelegate(this, function () {
-
- var enumerator = items.getEnumerator();
- while (enumerator.moveNext()) {
- var currentListItem = enumerator.get_current();
- alert(currentListItem.get_item("ID"));
- alert(currentListItem.get_item("Title"));
- alert(currentListItem.get_item("EmployeeName"));
- }
- }),
- Function.createDelegate(this, fail)
- );
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
-
- var contex = new SP.ClientContext("Your Site URL");
-
-
- var web = contex.get_web();
-
-
- var list = web.get_lists().getByTitle("Employee");
-
-
- var query = new SP.CamlQuery(); ctx.load(list);
-
- query.set_viewXml('<View><Query><Where><BeginsWith><FieldRef Name="EmployeeName" /><Value Type="Text">A</Value></BeginsWith></Where></Query></View>');
- var items = list.getItems(query);
-
-
- ctx.load(list);
- ctx.load(items);
- ctx.executeQueryAsync(
-
- Function.createDelegate(this, function () {
-
-
- var enumerator = items.getEnumerator();
- while (enumerator.moveNext()) {
- var currentListItem = enumerator.get_current();
- alert(currentListItem.get_item("ID"));
- alert(currentListItem.get_item("Title"));
- alert(currentListItem.get_item("EmployeeName"));
- }
- }),
- Function.createDelegate(this, fail)
- );
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
-
- var listname="Employee",
- url=_spPageContextInfo.webAbsoluteUrl;
-
- var item = $.extend({
- "__metadata": { "type": getListItemType(listname)}
- }, metadata);
- item.Title="MR";
- item.EmployeeName="Arvind Kushwaha""
-
-
- $.ajax({
- url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
- type: "POST",
- contentType: "application/json;odata=verbose",
- data: JSON.stringify(item),
- headers: {
- "Accept": "application/json;odata=verbose",
- "X-RequestDigest": $("#__REQUESTDIGEST").val(),
- "Content-Type":"application/json;odata=verbose",
- "X-HTTP-Method": "POST"
- },
- success: function (data) {
- success(data);
- },
- error: function (data) {
- failure(data);
- }
- });
b. Update Item
-
- var listname="Employee",
- id=1,
- url=_spPageContextInfo.webAbsoluteUrl;
- var item = $.extend({
- "__metadata": { "type": getListItemType(listname)}
- }, metadata);
- item.EmployeeName=’Arvind’;
-
-
- $.ajax({
- url: url + "/_api/web/lists/getbytitle('" + listname + "')/items(id)",
- type: "POST",
- contentType: "application/json;odata=verbose",
- data: JSON.stringify(item),
- headers: {
- "Accept": "application/json;odata=verbose",
- "X-RequestDigest": $("#__REQUESTDIGEST").val(),
- "Content-Type":"application/json;odata=verbose",
- "X-HTTP-Method": "MERGE"
- },
- success: function (data) {
- success(data);
- },
- error: function (data) {
- failure(data);
- }
- });
c. Delete Item
-
- var listname="Employee",
- id=1,
- url=_spPageContextInfo.webAbsoluteUrl;
-
-
- $.ajax({
- url: url + "/_api/web/lists/getbytitle('" + listname + "')/items(id)",
- type: "POST",
- contentType: "application/json;odata=verbose",
- headers: {
- "Accept": "application/json;odata=verbose",
- "X-RequestDigest": $("#__REQUESTDIGEST").val(),
- "Content-Type":"application/json;odata=verbose",
- "X-HTTP-Method": "DELETE"
- },
- success: function (data) {
- success(data);
- },
- error: function (data) {
- failure(data);
- }
- });
d. Get all Item
-
- var url = _spPageContextInfo.webAbsoluteUrl;
- listname="Employee";
-
-
- $.ajax({
- url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
- method: "GET",
- headers: { "Accept": "application/json; odata=verbose" },
- success: function (data) {
-
- console.log(data.d.results);
- },
- error: function (data) {
- failure(data);
- }
- });
e. Get Specific Item
-
- var url = _spPageContextInfo.webAbsoluteUrl;
-
-
- $.ajax({
- url: url + "/_api/web/lists/getbytitle('listname')/Items/?$select=Title,EmployeeName",
- method: "GET",
- headers: { "Accept": "application/json; odata=verbose" },
- success: function (data) {
-
- console.log(data.d.results);
- },
- error: function (data) {
- failure(data);
- }
- });
Note:
$select: Which column to retrieve in result.
$filter: What should be retrieve in result.
$expand: Retrieve the lookup column in result