我想为从数据库中检索到的几篇文章建立向上/向下投票系统,但我想为每篇文章添加 cookie 以限制投票数,因此 cookie 将在一天内过期,但我不知道在哪里添加适当的代码.
更多细节:
<script>
function vote(id, value) { // function vote with 2 arguments: article ID and value (+1 or -1) depending if you clicked on the arrow up or down
var dataFields = { 'id': id, 'value': value }; // We pass the 2 arguments
$.ajax({ // Ajax
type: "POST",
dataType: "text",//This for indicate that you'r expecting a text response from server
url: "WebService.asmx/updateVotes",
data: dataFields,
timeout: 3000,
success: function (dataBack) {
if(
$('#number' + id).html(dataBack);// div "number" with the new number
$('#arrow_up' + id).html('<div class="arrow_up_voted"></div>'); // We replace the clickable "arrow up" by the not clickable one
$('#arrow_down' + id).html('<div class="arrow_down_voted"></div>'); // We replace the clickable "arrow down" by the not clickable one
$('#message' + id).html('<div id="alertFadeOut' + id + '" style="color: green">Thank you for voting</div>'); // Diplay message with a fadeout
$('#alertFadeOut' + id).fadeOut(1100, function () {
$('#alertFadeOut' + id).text('');
});
},
error: function () {
$('#number' + id).text('Problem!');
}
});
}
</script>
上面的代码是一个脚本调用 ajax 方法来增加每次用户点击向上箭头时的投票数,反之则减少。
public string updateVotes(string id,int value)
{
System.Threading.Thread.Sleep(500); // delay for 2.5 seconds Network latency
post p = db.posts.Find(int.Parse(id));
// assign new values
p.totalVotes += value;
db.Entry(p).State = System.Data.EntityState.Modified;
db.SaveChanges();
string dataBack =p.totalVotes.ToString();
return dataBack;
}
这是网络方法。
现在我试着大声思考,如果 cookie 为空,我将以下函数编码为 ewxamine。
public bool enableVoting()
{
HttpCookie cookie = Request.Cookies["enableVote"];
if (Request.Cookies["enableVote"] != null)
{
return true;
}
else
{
return false;
}
}
我知道这是错的,但至少我试过了。
每当用户为文章投票时,还要在哪里添加一个 for each 循环以添加 cookie。?
foreach(post p in db.posts){
HttpCookie cookie = new HttpCookie("enableVote"+p.ID);
cookie.Value = "article:"+p.ID;
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
}