Asp.net实现点赞功能

本文介绍了如何在ASP.NET中实现点赞功能。通过在数据库中存储点赞用户,利用Ajax进行无刷新插入点赞记录,同时确保用户只能点赞一次。后端代码使用了GiveLikes.ashx来处理请求,并通过SQL查询获取点赞计数。

在数据库中用一组数据来存放已经点赞过的人名,用半角符号分开,用ajax实现点赞的人名插入,并规定只能点赞一次。

$.ajax({
    type: "GET",
    cache: false,
    url: 'GiveLikes.ashx',
    dataType: 'text',
    data: {
        UID: uid
    },
    beforeSend: function () { },
    success: function (data) {
        var a = ($('#Likes_No').text())*1+1*1;
        $('#Likes_No').html(a);
        $("#Likes_IMG").attr('disabled', true);
    },
    error: function (XmlHttpRequest, textStatus, errorThrown) {
        console.log("点赞错误!");
    }
});

后端GiveLikes.ashx代码中的代码

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Windows.Forms;


namespace Arena
{
    /// <summary>
    /// GiveLikes 的摘要说明
    /// </summary>
    public class GiveLikes : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string LogUID = Environment.UserName;
            string UID = context.Request["UID"];
            
            if (UID == "")
            {
                UID= Environment.UserName;
            }
            
            using (SqlConnection conn = new SqlConnection("Server=.;Database=Arena;User ID=sa;Password=yymm7010212"))
            {
                string Sql= string.Empty;
                conn.Open();
                SqlCommand comm = new SqlCommand();
                comm.CommandType = CommandType.Text;
                comm.CommandText = "SELECT Likes from Arena.dbo.PersonalInfo WHERE UID='"+ UID + "'";
                comm.Connection = conn;
                using (SqlDataReader DataReader = comm.ExecuteReader())
                {
                    DataReader.Read();
                    if ((DataReader["Likes"] is System.DBNull))//如果目前还没有任何人点赞
                    {
                        Sql = "Update Arena.dbo.PersonalInfo set Likes='" + LogUID + ",' WHERE UID='" + UID + "'";
                    }
                    else
                    {
                        Sql = "Update Arena.dbo.PersonalInfo set Likes=Likes+'" + LogUID + ",' WHERE UID='" + UID + "'";
                    }
                }
                comm.CommandText = Sql;
                comm.ExecuteNonQuery();
                comm.Dispose();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

并用sql查询语句查询到数据库中点赞的人数

comm.CommandText = "SELECT LEN(Likes)-len(replace(Likes,',','')) AS num FROM Arena.dbo.PersonalInfo WHERE UID='" + UID + "'";

数据库中
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值