private AnswerVote CreateVote(int aId,int qId,int uId,int vote) { return answerVote = new AnswerVote() { QId=qId,AId=aId,UId=uId,Vote=(byte)vote}; }
public JsonResult Vote(int qid,int aid,string vt) { Answer answer = new Answer(); bool isCancel = false; int pro=0,con = 0; user = GetUser(); if (user != null) { using (club = new ClubEntities()) { answer = club.Answers.Where(a => a.Id == aid).FirstOrDefault(); if (answer == null) { context = "该问题不存在!"; } else{ answerVote = club.AnswerVotes.Where(av => av.AId == aid && av.QId == qid && av.UId == user.Id).FirstOrDefault(); if (vt.Equals("up")) { if (answerVote == null) { club.AnswerVotes.Add(CreateVote(aid,qid,user.Id,1)); answer.Agree = answer.Agree + 1; } else { if (answerVote.Vote == 0) { answerVote.Vote = 1; answer.Oppose = (answer.Oppose - 1) > 0 ? (answer.Oppose - 1) : 0; answer.Agree = answer.Agree + 1; } else { club.AnswerVotes.Remove(answerVote); answer.Agree = (answer.Agree - 1) > 0 ? (answer.Agree - 1) : 0; isCancel = true; } } } if (vt.Equals("down")) { if (answerVote == null) { club.AnswerVotes.Add(CreateVote(aid,qid,user.Id,0)); answer.Oppose = answer.Oppose + 1; } else { if (answerVote.Vote == 1) { answerVote.Vote = 0; answer.Agree = (answer.Agree - 1) > 0 ? (answer.Agree - 1) : 0; answer.Oppose = answer.Oppose + 1; } else { club.AnswerVotes.Remove(answerVote); answer.Oppose = (answer.Oppose - 1) > 0 ? (answer.Oppose - 1) : 0; isCancel = true; } } } if(club.SaveChanges()>=0){ status=Status.success; context="操作成功!"; } pro = answer.Agree; con = answer.Oppose; } } } else { return Json(new {status=Status.warning.ToString(),url="/account/login?returnurl=/ask/show/"+qid },JsonRequestBehavior.AllowGet); } return Json(new { status = status.ToString(), context = context,iscancel=isCancel,pro=pro,con=con,op=vt }, JsonRequestBehavior.AllowGet); }