Friday, 6 April 2012

Get List and set list Items using Ecma script Client Object model using SharePoint 2010

How to Get List item and set list Items using Ecma script ( Client Object model) using SharePoint SP 2010 :

For my scenario, I have  to update the news count of news list ("NewsListName") based on the user viewed click count.
So, i have to get the current value of custom list item and update the same with the increment value of 1.

The following code will demonstrate how to get and update list item from client side script itself by using ecma script (client object model) in Sp 2010.

ecma script is a kind of java script which is used to update items without using any page postback / server side code in sharepoint 2010.

Sample code example:

source:

<a href="#" onclick="updatenewscount(newsid);">news title</a>

script:
 
<SharePoint:ScriptLink Name="SP.js" runat="server" LoadAfterUI="true" Localizable="false" />
-OR-
<script language="ecmascript" type="text/ecmascript" src="SP.js" />

<script language="ecmascript" type="text/ecmascript">
var newslist;
var web;
var context;
var newsid;
var newsitem;
var newscount = "Count";


function updatenewscount(itemId)
{
    newsid = itemId;

    context = new SP.ClientContext.get_current();
    web = context.get_web();
    newslist = web.get_lists().getByTitle("NewsListName");
    newsitem = newslist.getItemById(newsid);

    context.load(newslist);
    context.load(newsitem);
    context.executeQueryAsync(OnNewslistsLoaded);
}

function OnNewslistsLoaded()
{
    var currentcount = newsitem.get_item(newscount);

    newsitem.set_item(newscount, parseInt(currentcount)+1);
    newsitem.update();

    // Submit the query to the server
    context.load(newsitem);
    context.executeQueryAsync(OnNewsUpdated, OnError);   
}

function OnNewsUpdated (args)
{
     Alert(‘news count updated’);
}

function OnError(sender, args)
{
    alert(args.get_message());
}
</script>

No comments:

Post a Comment