LIKE or UNLIKE a list item programmatically

If Likes are enable in the Rating Settings of a list then users can like/unlike a list item using the UI. A list item can also be liked/unliked programmatically.
There are to ways to like/unlike an item programmatically.

1.Using Reputation class.

This is the recommended way.Reputation class is used to set Likes and Ratings for list items.
To like an item:

    Reputation.SetLike(listID, itemID, true);

To unlike an item:

	Reputation.SetLike(listID, itemID, false);

2.Directly by updating the item’s LikesCount and LikedBy fields.

    SPFieldUserValueCollection likedBy = new SPFieldUserValueCollection(web, item["LikedBy"].ToString());

	SPUser user = web.EnsureUser("YOURDOMAIN\\USERNAME");
	SPFieldUserValue newUser = new SPFieldUserValue(web, user.ID, user.Name);
	
	likedBy.Add(newUser);
	int likes = likedBy.Distinct().Count();
	item["LikesCount"] = likes;
	item["LikedBy"] = likedBy;
	item.SystemUpdate(false);

If you increase LikesCount without adding new user in LikedBy field the item will show the increased number of likes temporary but with the first like/unlike from a user using the UI the number of likes will be automatically corrected to reflect the number of users that have liked the item.

To unlike decrease LikeCount field value and remove the user from LikedBy.

Advertisements

One Response to LIKE or UNLIKE a list item programmatically

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: