Search This Blog

Tuesday, August 16, 2016

CRUD Operation IN SharePoint 2013 SSOM/JSOM/CSOM/SPSerVices/Rest API/Angular JS with Rest API


1-    Add, Update and Delete List Items  in SharePoint SSOM

using (SPSiteoSPsite = new SPSite("http://website url/"))
{
using (SPWeboSPWeb = oSPsite.OpenWeb())
      {
oSPWeb.AllowUnsafeUpdates = true;

            // Fetch the List
SPList list = oSPWeb.Lists["MyList"];

            //Add a new item in the List
SPListItemitemToAdd = list.Items.Add();
itemToAdd["Title"] = "Test Title";
itemToAdd["Description"] = "Test Description";
itemToAdd.Update();

            // Get the Item ID
listItemId = itemToAdd.ID;

// Update the List item by ID
SPListItemitemToUpdate = list.GetItemById(listItemId);
itemToUpdate["Description"] = "Changed Description";
itemToUpdate.Update();

            // Delete List item
SPListItemitemToDelete = list.GetItemById(listItemId);
itemToDelete.Delete();

oSPWeb.AllowUnsafeUpdates = false;
       }
}



2-Add, Update and Delete List Items  in SharePoint CSOM

           //  Common for All
stringsiteUrl = "https://ngo.com/NGOHR";
ClientContextclientContext = newClientContext(siteUrl);
            List oList = clientContext.Web.Lists.GetByTitle("StudentDetails");

// Get Records
CamlQuerycamlQuery = newCamlQuery();
camlQuery.ViewXml =
                @"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='StudentName'/>
<Value Type='Text'>Ram</Value>
</Eq>
</Where>
</Query>
<RowLimit>100</RowLimit>
</View>";
ListItemCollectionlistItems = oList.GetItems(camlQuery);
clientContext.Load(
listItems,
items => items
                     .Include(
item => item["Title"],
item => item["StudentName"]));
clientContext.ExecuteQuery();
foreach (ListItemlistIteminlistItems)
            {
Console.WriteLine("Title: {0}", listItem["Title"]);
Console.WriteLine("StudentName: {0}", listItem["StudentName"]);
            }

//  Insert Records 
ListItemCreationInformationlistCreationInformation = newListItemCreationInformation();
ListItemoListItem = oList.AddItem(listCreationInformation);
oListItem["Title"] = "Hello World";
oListItem.Update();
clientContext.ExecuteQuery();


//  Update  Records

oListItem = oList.GetItemById(17);
oListItem["Title"] = "Hello World Updated!!!";
oListItem.Update();
clientContext.ExecuteQuery();


//  Delete  Records

oListItem = oList.GetItemById(36);
oListItem.DeleteObject();

clientContext.ExecuteQuery();

 

3-Save, Update, and Delete List Items Using JavaScript (JSOM)

1-Save
varsiteUrl = '/sites/MySiteCollection';
functioncreateListItem() {
varclientContext = newSP.ClientContext(siteUrl);
varoList = clientContext.get_web().get_lists().getByTitle('Announcements');
varitemCreateInfo = newSP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Title', 'My New Item!');
oListItem.set_item('Body', 'Hello World!');
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

functiononQuerySucceeded() {
alert('Item created: ' + oListItem.get_id());
}
functiononQueryFailed(sender, args) {
alert('Request failed. ' +args.get_message() + '\n' + args.get_stackTrace());
}

2-Update
varsiteUrl = '/sites/MySiteCollection';
functionupdateListItem() {
varclientContext = newSP.ClientContext(siteUrl);
varoList = clientContext.get_web().get_lists().getByTitle('Announcements');
this.oListItem = oList.getItemById(3);
oListItem.set_item('Title', 'My Updated Title');
oListItem.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), 
Function.createDelegate(this, this.onQueryFailed));
}
functiononQuerySucceeded() {
alert('Item updated!');
}
functiononQueryFailed(sender, args) {
alert('Request failed. ' +args.get_message() + '\n' + args.get_stackTrace());
}

 

3-Delete
varsiteUrl = '/sites/MySiteCollection';
functiondeleteListItem() {
this.itemId = 2;
varclientContext = newSP.ClientContext(siteUrl);
varoList = clientContext.get_web().get_lists().getByTitle('Announcements');
this.oListItem = oList.getItemById(itemId);
oListItem.deleteObject();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),
 Function.createDelegate(this, this.onQueryFailed));
}
functiononQuerySucceeded() {
alert('Item deleted: ' + itemId);
}
functiononQueryFailed(sender, args) {
alert('Request failed. ' +args.get_message() + '\n' + args.get_stackTrace());
}
4-Get Items
varsiteUrl = '/sites/MySiteCollection';
functionretrieveListItems() {
varclientContext = newSP.ClientContext(siteUrl);
varoList = clientContext.get_web().get_lists().getByTitle('Announcements');
varcamlQuery = newSP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' + 
'<Value Type=\'Number\'>1</Value></Geq>
</Where></Query><RowLimit>10</RowLimit></View>');
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), 
Function.createDelegate(this, this.onQueryFailed));        
}
functiononQuerySucceeded(sender, args) {
varlistItemInfo = '';
varlistItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
varoListItem = listItemEnumerator.get_current();
listItemInfo += '\nID: ' + oListItem.get_id() + 
'\nTitle: ' + oListItem.get_item('Title') + 
'\nBody: ' + oListItem.get_item('Body');
    }
alert(listItemInfo.toString());
}
functiononQueryFailed(sender, args) {
alert('Request failed. ' +args.get_message() + '\n' + args.get_stackTrace());
}

4-Save, Update, and Delete List Items Using JavaScript (Rest API)

1-Save
functionAddListItem() 
varindustryVal = $("#Industry").val(); 
var Company = $("#Company").val(); 
     $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items",
type: "POST",
data: JSON.stringify
               ({
                                '__metadata': {'type': 'SP.Data.EMPMasterListItem' },
                                "Title": Company,
                                "Industry":industryVal
               }),

headers:
              {
                "Accept": "application/json;odata=verbose",
                 "content-type": "application/json; odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
              },

success: function(data)
              {
retriveListItem(); 
alert("Item added successfully!");
              },

error: function(err)
              {
alert("Error while adding item: " + JSON.stringify(err));
              }
          });

 } 



2-Update

functionUpdateListItem () {
varindustryVal = $("#Industry").val(); 
var Company = $("#Company").val(); 
           $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items(1)",
type: "POST",
data: JSON.stringify
              ({
              '__metadata': {'type': 'SP.Data.EMPMasterListItem' },
              "Title": Company,
              "Industry":industryVal
              }),
headers:
              {
                   "Accept": "application/json;odata=verbose",
                   "content-type": "application/json; odata=verbose",
                   "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                   "X-HTTP-Method": "MERGE",
                   "If-Match": "*"
               },
success: function(data)
              {
                retriveListItem();
                alert("Item updated successfully!");
              },
error: function(err)
              {
alert("Error while updating item: " + JSON.stringify(err));
              }

          });

      }

3-Delete
functionDeleteListItem()
  {
       $.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items(1)",
type: "POST",
headers: {
                       "Accept": "application/json;odata=verbose",
                       "content-type": "application/json; odata=verbose",
                       "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                       "X-HTTP-Method": "DELETE",
                       "If-Match": "*"
                        },
success: function(data){
retriveListItem();
alert("Item deleted successfully!");
                            },
error: function(err){
alert("Error while deleting item: " + JSON.stringify(err));
                            }

          });
    }




4- Get Items
functionretriveListItem() 
                                               
{
varresultGridHtmlMySubmission=''
  $.ajax (
          {
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('EMPMaster')/items?$select=Title,Industry",
type: "GET",
data: JSON.stringify,
headers:
{
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"IF-MATCH": "*",
"X-HTTP-Method": null
},
cache: false,
success: function(data)  
for (vari = 0; i<data.d.results.length; i++)
{
var item = data.d.results[i];
resultGridHtmlMySubmission+='<tr>';
resultGridHtmlMySubmission+='<tdalign="center"   valign="middle"><span title="Sr.No."><b>'+item.Title+'</b></span></td>';
resultGridHtmlMySubmission+='<td align="center" valign="middle"><span title="Sr.No."><b>'+item.Industry+'</b></span></td>';
resultGridHtmlMySubmission+='</tr>';

  }
$("#tbodycontent").html(resultGridHtmlMySubmission);
},
error: function(data)
{
// $("#ResultDiv").empty().text(data.responseJSON.error);
}
});
}

5-Save, Update, and Delete List Items Using JavaScript (SP Services)

1-Save
functionAddNewListItem(title)
{
$().SPServices({
operation:"UpdateListItems",
async: false,
batchCmd: "New",
listName: "StudentDetails",
valuepairs:[["Title",'Harmeet  Singh']],
completefunc:function(xData, Status)
{
alert("Item inserted");
}
});
}
2-Update

functionUpdateListItem(title)
{
$().SPServices({
operation:"UpdateListItems",
async: false,
batchCmd: "Update",
listName: "StudentDetails ",
ID: 3,
valuepairs:[["Title",”Mahesh”]],
completefunc:function(xData, Status)
{
alert("Item Updated");
}
});
}

3-Delete
functionDeleteListItem()
{
$().SPServices({
operation:"UpdateListItems",
async: false,
batchCmd: "Delete",
listName: "StudentDetails",
ID: 3,
completefunc:function(xData, Status)
{
alert("Item Deleted");
}
});
}



4- Get Items
functionGetItem()
{
$().SPServices({
operation: "GetListItems", 
async: false, 
listName: "StudentDetails", 
CAMLViewFields: "<ViewFields><FieldRef Name='Title' /></ViewFields>", 
completefunc: function (xData, Status)
 $(xData.responseXML).find("[nodeName='z:row']").each(function() { 
varliHtml = "<li>" + $(this).attr("ows_Title") + "</li>"; 
        $("#ulTasks").append(liHtml); 
      }); 
    } 
  });
}

 


6-Save, Update, and Delete List Items Using JavaScript (Angular JS)

1Get Items

varmyAngApp = angular.module('SharePointAngApp', ['ui.bootstrap', 'ngResource']);
myAngApp.controller('spCustomerController', function ($scope, $http)
{
$scope.eEditable= -1;
$http({
method: 'GET',
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('UserTest')/items?$select=Title,Employee,Company,ID",
headers:
{
"Accept": "application/json;odata=verbose"
}
}).success(function (data, status, headers, config) {
$scope.customers = data.d.results;
$scope.totalItems = $scope.customers.length;
$scope.numPerPage = 5;
$scope.currentPage = 1;
$scope.paginate = function (value) {
var begin, end, index;
begin = ($scope.currentPage - 1) * $scope.numPerPage;
end = begin + $scope.numPerPage;
index = $scope.customers.indexOf(value);
return (begin <= index && index < end);
};

// var a= $scope.customers;
}).error(function (data, status, headers, config) {

});

 

1Get ItemsBy ID


//$scope.customers = [];
$scope.getByDataID = function (customer) {
varcustomerId= customer;
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('UserTest')/getitembyid("+customerId+")/?$select=Title,Employee,Company,ID",
type: "GET",
headers:
{
"Accept": "application/json;odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(data){
$( "#btnupdateval" ).prop( "disabled", false );
$scope.customer=data.d;
$('#txtItemId').val(data.d.Id);
$('#txttitle').val(data.d.Title);
$('#txtcompany').val(data.d.Employee);
$('#txtemployee').val(data.d.Company);
$( "#btnsave" ).prop( "disabled", true );

},
error: function(err){
alert("Error while fetching list item: " + JSON.stringify(err));
}
});
};
1-Save

$scope.Save = function () {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('UserTest')/items",
type: "POST",
data: JSON.stringify
({
'__metadata': {'type': 'SP.Data.UserTestListItem' },
"Title": $scope.customer.Title,
"Employee":$scope.customer.Employee,
"Company":$scope.customer.Company               }),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function(data){
alert("Item added successfully!");
},
error: function(err){
alert("Error while adding item: " + JSON.stringify(err));
}
});};
4-Update


$scope.Update = function () {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('UserTest')/items("+$scope.customer.ID+")",
type: "POST",
data: JSON.stringify({

'__metadata': {'type': 'SP.Data.UserTestListItem' },
"Title": $scope.customer.Title,
"Employee":$scope.customer.Employee,
"Company":$scope.customer.Company
}),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},
success: function(data){
alert("Item updated successfully!");
},
error: function(err){
alert("Error while updating item: " + JSON.stringify(err));
}

});

};
5-Delete


$scope.Delete= function (customer) {
varcustomerId=customer;
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('UserTest')/items("+customerId+")",
type: "POST",
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"X-HTTP-Method": "DELETE",
"If-Match": "*"
},
success: function(data){
alert("Item deleted successfully!");
},
error: function(err){
alert("Error while deleting item: " + JSON.stringify(err));
}
});
};});








No comments:

Post a Comment