Search This Blog

Tuesday, March 1, 2016

SharePoint 2013: How to edit list item using REST services

We learned how to get, add and delete the list item. In this post we will learn how to edit the list item. This operation is also simple; this requires two steps or two calls. First get item id and then edit it. We will see in detail how to do it in this article.

The REST URL remains same for update operations.

URL to edit the list item: /_api/web/lists/getbytitle('StudentsList')/items(itemID)

Parameters required for REST services in case of edit operations are values of fields which needs to be updated. Also don't forget to provide the metadata type which is also known as list item type: Type.

Then next important parameter in headers  is If-match which requires e-tag. E-tag is used in REST services for managing the concurrency. If you put e-tag: "*" then it means override other changes forcefully. The other way to get the e-tag is get it from the response of first call and use this as a parameter in edit operation. Also don't forget to give X-HTTP-METHOD in headers section. In this way you can perform edit operations.

Following is the complete code snippet to edit list item using REST api:

function EditListItems()
{
  var id = $("#txtId").val();
var name = $("#txtName").val();
var class1 = $("#txtClass").val();
var age = $("#txtAge").val();
var city = $("#txtCity").val();
$.ajax({

        url: "/_api/web/lists/getbytitle('StudentsList')/items(" + id + ")",    //data.__metadata.uri    
        data: JSON.stringify({'__metadata': { 'type': 'SP.Data.StudentsListListItem' }, 'Title': 'Mr.', 'Name': name, 'Class' : class1, 'Age': age,'City': city }),
        type: "POST",        
        headers: {
                   "ACCEPT": "application/json;odata=verbose",
                   "content-type": "application/json;odata=verbose",
                   "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                   "IF-MATCH": "*", //data.__metadata.etag
                   "X-HTTP-Method": "MERGE"
        },
        success: function (data) {
            alert("Updated successfuly");
        },
        error: function (error) {
            alert(JSON.stringify(error));
        }

     });
}

No comments:

Post a Comment