- 在ASP.NET使用ajax时基本上每个操作都要新建一个.ashx处理程序,页面很多,每个页面的操作也很多,这样的话项目就会产生新建很多很多的.ashx页面,能不能把方法写在后台中,然后Jquery直接调用呢?答案自然是可以的,这样做的话程序就看起来简洁多了。
- 前段时间下载****上的资源时,我发现它们添加评论的那个功能蛮酷的,点一下 添加 按钮,评论即时显示在了最上方。下午想了下,写了一个Demo,其中 添加评论 的功能就是通过jquery调用后台方法完成的。具体代码如下:
前台页面代码CsdnAddComment.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CsdnAddComment.aspx.cs"
Inherits="Study.CsdnAddComment" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>仿****添加评论</title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnComment").click(function () {
var txtComment = $("#txtComment").val();
$.ajax({
type: "post",
url: "CsdnAddComment.aspx/AddComment",
data: " { 'comment':'" + txtComment + "'}",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (message) {
$("#Comment").append('<div class="NewComment">' + txtComment + '</div>');
$("#NewComment").next().slideToggle();
}
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<center>
<div style="width: 50%">
新闻列表:
<asp:Repeater ID="rpNews" runat="server">
<ItemTemplate>
<div>
<%#DataBinder.Eval(Container.DataItem, "news_title")%>
</div>
<hr />
</ItemTemplate>
</asp:Repeater>
<div id="Comment">
</div>
</div>
<div>
<textarea id="txtComment" rows="8" cols="70"></textarea><br />
<input type="button" value="评论" id="btnComment"/>
</div>
</center>
</form>
</body>
</html>
后台代码CsdnAddComment.aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services; namespace Study
{
public partial class CsdnAddComment : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.GetNewsList();
}
} /// <summary>
/// 获取新闻列表
/// </summary>
private void GetNewsList()
{
News n = new News();
List<News> newsList = n.GetNewsList();
rpNews.DataSource = newsList;
rpNews.DataBind();
} //添加新评论
[WebMethod]
public static string AddComment(string comment)
{
string sqlStr = "insert into tb_news(news_title,news_content,news_time,news_readtimes) values('" + comment + "','内容','2011/6/8','100')";
if (SQLHelper.ExecuteNonQuery(sqlStr) > 0)
{
return "success";
}
else
{
return "failed";
}
}
}
}