Sunday, October 11, 2009

How to Insert Item in Sharepoint List using WebService with Javascript

Without using Sharepoint API we can achieve by OOB. In following code I have inserting items in MyList and ID and Title.

You can call the from a button with the following code

<input type="button" value="Save List Item" onclick="javascript:SaveListItem();">

function SaveListItem()
{
var soapRequest = '<?xml version="1.0" encoding="utf-8"?>' +
'<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">' +
' <soap12:Body>'+
' <UpdateListItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">'+
' <listName>TestList</listName>'+
' <updates>'+
'<Batch OnError="Continue">'+
' <Method ID="1" Cmd="New">'+
' <Field Name="ID">New</Field>'+
' <Field Name="Title">TestData</Field>'+
' </Method>'+
'</Batch>'+
' </updates>'+
' </UpdateListItems>'+
' </soap12:Body>'+
'</soap12:Envelope>';
xmlHttp=new XMLHttpRequest();
xmlHttp.open('post', 'http://ServerName/SiteCollection/_vti_bin/Lists.asmx', true);
xmlHttp.setRequestHeader('Content-Type','application/soap+xml; charset=utf-8');
xmlHttp.send(soapRequest);
}

Saturday, October 3, 2009

How to Delete attachment from an Item in Sharepoint List

public static void DeleteAttachements(int id)

{
using (SPSite site = new SPSite("http://portal"))
{
using (SPWeb web = site.OpenWeb())
{
SPListItem listItem = web.Lists["mylist"].GetItemById(id);
List<string> fileNames = new List<string>();
foreach (string fileName in listItem.Attachments)
{
fileNames.Add(fileName);
}
foreach(string fileName in fileNames)
{
listItem.Attachments.Delete(fileName);
}
listItem.update();
}
}
}