一般评论可以点赞提高互动性。不可以重复点,在评论库里加一个文本型字段,
该字段存储已经提交过“赞”的用户,用符号分割,建议逗号分割。
在点赞之前检查用户是否已经在列表中。另外,如果用户没有登录也希望可以点赞
除了使用用户信息还可以储存ip地址,这样一个ip也可以点赞一次,无需登录。
下面是实现的方法,仅供参考。
//当用户点赞评论的时候发生!
protected void Unnamed_Click(object sender, EventArgs e)
{
bool isagreed = false;
string username = "";
try
{
username = Convert.ToString(Session["username"]);
}
catch (Exception)
{
}
if (username == "")
{
string ip;
if (Context.Request.ServerVariables["HTTP_VIA"] != null) // using proxy
{
ip = Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); // Return real client IP.
}
else// not using proxy or can't get the Client IP
{
ip = Context.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP.
}
username = ip;
}
LinkButton btn = (LinkButton)sender;
Int64 commentID = Convert.ToInt64(btn.CommandArgument);
//数据库连接字符串
string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\storage\\users.accdb";
using (OleDbConnection con = new OleDbConnection(conStr))
{
string cmdStr = "SELECT [statis],[agreeUser] FROM [comment] where [id]=" + commentID + "";
int commentStatis = 0;
string agreeUser = "";
//打开连接
con.Open();
using (var cmd = new OleDbCommand(cmdStr, con))
{
using (OleDbDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())//
{
commentStatis = reader.GetInt32(0) + 1;
try
{
agreeUser = reader.GetString(1);
}
catch (Exception)
{
}
string[] agreeUsers = agreeUser.Split(',');
for (int i = 0; i < agreeUsers.Count(); i++)
{
if (username == agreeUsers[i])
{
isagreed = true;//已经点过赞了!
break;
}
}
agreeUser += username + ",";
}
else
{
isagreed = true;//数据库读取失败,等同于 点过赞不更新数据库
Response.Write("<script>alert('哎呀,出了点状况。数据库出错啦')</script>");
}
}
if (!isagreed)//如果没点过赞
{
cmd.CommandText = "UPDATE [comment] set [statis]=" + commentStatis + " ,[agreeUser]='" + agreeUser + "' where [id]=" + commentID + "";
cmd.ExecuteNonQuery();
}
}
con.Close();
//Response.Write("<script>alert('提交成功');location.href=" + Request.Url + ";</script>");
Response.AddHeader("Refresh", "0");
}
}