Friday, February 8, 2013

SharePoint 2010 OOTB ratings, how to get individual ratings for any list item or by particular user

SharePoint 2010 provides out of the box feature to enable users to rate any list item. This can be achieved with few steps of configuration. Well this is actually not the context of this post to show you how to enable ratings on any list and all the stuff available through out of the box functionality. Let's talk about something which is not available out of the box and you might come across such requirement while using out of the box rating feature.
The out of the box rating control provides you information about average rating done by distinct users and number of distinct users who have rated a particular item. In this post we will discuss how to fetch individual ratings done for a particular list item and ratings done by particular user.

1. Individual rating details done for a list item:
Following code can be used to fetch individual ratings done for a list item (SPListItem listItem1) belongs to list (SPList list1):

SPSite site = SPContext.Current.Site;
SPWeb web = SPContext.Current.Web;
SPServiceContext context = SPServiceContext.GetContext(site);
SocialRatingManager socialRatingManager = new SocialRatingManager(context);
string listItemURL = web.Url + "/_layouts/listform.aspx?PageType=4&ListId={" + list1.ID.ToString() + "}&ID=" + listItem1.ID;

SocialRating[] ratings = socialRatingManager.GetRatings(new Uri(listItemURL));
foreach (SocialRating rating in ratings)
{
    if (rating.Rating > 0)
    {

         string userName = rating.Owner.DisplayName,
         int rating = rating.Rating;
    }


2. Ratings done by particular user:
Following code can be used to fetch ratings done by particular user (SPUser user1):

SPSite site = SPContext.Current.Site;
SPServiceContext context = SPServiceContext.GetContext(site);
SocialRatingManager socialRatingManager = new SocialRatingManager(context);
UserProfileManager profileManager = new UserProfileManager(context);
UserProfile profile = profileManager.GetUserProfile(user1.LoginName.ToString());

SocialRating[] ratings = socialRatingManager.GetRatings(profile);
foreach (SocialRating rating in ratings)
{
    if (rating.Rating > 0)
    {

         string title = rating.Title,
         int rating = rating.Rating;
    }


1 comment:

  1. I thought the rating was for the whole list, not the list item?????

    ReplyDelete