/// <summary> /// /// </summary> /// <param name="itemID"></param> /// <param name="likeCount">1/-1点赞和取消赞</param> private void SaveLikeUnLike(int itemID, int likeCount) { SPUser loginUser = SPContext.Current.Web.CurrentUser; Guid webID = SPContext.Current.Web.ID; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite mySite = new SPSite(SPContext.Current.Site.Url)) { using (SPWeb thisWeb = mySite.AllWebs[webID]) { thisWeb.AllowUnsafeUpdates = true; try { string listUrl = Page.Request.FilePath;; SPList list = thisWeb.GetList(listUrl); SPListItem lstItem = list.GetItemById(itemID); SPFieldUserValueCollection users = lstItem["LikedBy"] as SPFieldUserValueCollection; SPFieldUserValue userValue = new SPFieldUserValue(thisWeb, loginUser.ID, loginUser.Name); if (users != null) { lstItem["LikesCount"] = (double)lstItem["LikesCount"] + likeCount; if (likeCount > 0)//点赞 { users.Add(userValue); lstItem["LikedBy"] = users; } else //取消赞 { for (int i = 0; i < users.Count; i++) { if (users[i].LookupId == loginUser.ID) { users.RemoveAt(i); break; } } lstItem["LikedBy"] = users; } } else { lstItem["LikedBy"] = loginUser; lstItem["LikesCount"] = likeCount; } lstItem.Update(); } catch (Exception ex) { this.Controls.Add(new LiteralControl(ex.ToString())); } thisWeb.AllowUnsafeUpdates = false; } } }); }