方法一:通过创建一个没有内容的窗体
后台:
public partial class Ajax_ShoppingCart : System.Web.UI.Page
{
bookdbDataContext bdc = Connect.bookdb();
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
if(Request.Form["method"]!=null)
{
switch (Request.Form["method"].ToString())
{
//添加商品至购物车
case "addToCart":
Response.Write(addToCart());
break;
//获得购物车
case "showCart":
Response.Write(showCart());
break;
//从购物车中删除商品
case "removeCart":
Response.Write(removeCart());
break;
//减少购物车中某一商品的数量
case "redCount":
Response.Write(redCount());
break;
//增加购物车中某一商品的数量
case "addCount":
Response.Write(addCount());
break;
default:
break;
}
}
}
} protected string tid
{
get
{
if (Request.Form["tid"] != null)
{
return Request.Form["tid"].ToString();
}
else
{
return "";
}
}
}
/// <summary>
/// 添加至购物车
/// </summary>
/// <returns></returns>
protected string addToCart()
{
int Count = ;
string message = string.Empty;
if (Request.Form["count"] != null)
{
Int32.TryParse(Request.Form["count"].ToString(), out Count);
}
if (Count > || Count < )
{
return JsonConvert.SerializeObject(new { status = , message = "书籍数量不对,不能超过5张哦" });
}
var tic = bdc.Book.SingleOrDefault(obj => obj.ID == Convert.ToInt32(tid));
if (tic != null)
{
Common.Book t = new Common.Book();
t.ID = tid;
t.Count = Count;
t.Name = tic.Name;
t.Price = tic.Price;
int result = ShoppingCartHelper.addCart(t);
switch (result)
{
case -:
return JsonConvert.SerializeObject(new { status = , message = "同一书籍不能购买超过5本哦!" });
case :
return JsonConvert.SerializeObject(new { status = , cart = ShoppingCartHelper.getShoppingCart(), message = "成功加入购物车!" });
default:
return null;
}
}
else
{
return JsonConvert.SerializeObject(new { status = , message = "不存在此书籍,请您重新选择!" });
}
} /// <summary>
/// 获得购物车
/// </summary>
/// <returns></returns>
protected string showCart()
{
return JsonConvert.SerializeObject(new { cart = ShoppingCartHelper.getShoppingCart() });
} /// <summary>
/// 从购物车中移除商品
/// </summary>
/// <returns></returns>
protected string removeCart()
{
int result = ShoppingCartHelper.removeCart(tid);
switch (result)
{
case -:
return JsonConvert.SerializeObject(new { status = , message = "离开太久啦,购物车已经空空了,您重新购买吧" });
default:
return JsonConvert.SerializeObject(new { status = , cart = ShoppingCartHelper.getShoppingCart() });
}
} /// <summary>
/// 减少购物车中某一件商品的数量
/// </summary>
/// <returns></returns>
protected string redCount()
{
int result = ShoppingCartHelper.reduceCart(tid);
switch (result)
{
case -:
return JsonConvert.SerializeObject(new { status = , message = "离开太久啦,购物车已经空空了,您重新购买吧" });
default:
return JsonConvert.SerializeObject(new { status = , cart = ShoppingCartHelper.getShoppingCart() });
}
} /// <summary>
/// 增加购物车中某一件商品的数量
/// </summary>
/// <returns></returns>
protected string addCount()
{
int result = ShoppingCartHelper.addCart(tid);
switch (result)
{
case -:
return JsonConvert.SerializeObject(new { status = , message = "离开太久啦,购物车已经空空了,您重新购买吧" });
default:
return JsonConvert.SerializeObject(new { status = , cart = ShoppingCartHelper.getShoppingCart() });
}
}
}
后台代码
前台:
function ShowNewList(d,t) {
var _url = "/Data_ajax/Ajax_ShoppingCart.aspx";//Data_ajax只是一个文件夹名字,随便怎么取,但是,该页面的aspx界面中,不能出现空格和内容,就是一个空的界面什么对没有
var obj = {
method: "addToCart",
Id: d //在后台可以用Reques.Form["Id"]获取参数值
};
jQuery.ajax({
type: "POST",
url: _url,
data: obj,
dataType: "json",
success: function (x) {
ShowNewList1(x);
}
});
}
前台代码
购物车类:
namespace Ipow.CMS.Helper
{
public static class ShoppingCartHelper
{
/// <summary>
/// 获取购物车
/// </summary>
/// <returns></returns>
public static shoppingCart getShoppingCart()
{
shoppingCart cart = new shoppingCart();
if (HttpContext.Current.Session["cart"] != null)
{
cart = HttpContext.Current.Session["cart"] as shoppingCart;
}
return cart;
} /// <summary>
/// 加入购物车
/// </summary>
/// <param name="tic">门票</param>
/// <param name="CategoryID">门票类别</param>
/// <returns></returns>
public static int addCart(ticket tic, int CategoryID)
{
int result = ;
shoppingCart cart = getShoppingCart();
if (cart.CategoryID == )
{
cart.CategoryID = CategoryID;
cart.TotalPrice = tic.ticketPrice * tic.ticketCount;
List<ticket> list = new List<ticket>();
list.Add(tic);
cart.tickets = list;
}
else
{
if (cart.CategoryID != CategoryID && cart.tickets.Count() != )
{
//不同园区门票不能加入同一个购物车
result = -;
}
else
{
ticket t1 = cart.tickets.SingleOrDefault(obj => obj.ticketID == tic.ticketID);
//如果已存在同样的门票,则增加门票数量
if (t1 != null)
{
if (t1.ticketCount + tic.ticketCount <= )
{
t1.ticketCount += tic.ticketCount;
cart.TotalPrice += tic.ticketPrice * tic.ticketCount;
cart.CategoryID = CategoryID;
}
else
{
//门票数量超过5张
result = -;
}
}
//不存在则添加
else
{
cart.TotalPrice += tic.ticketPrice * tic.ticketCount;
cart.CategoryID = CategoryID;
cart.tickets.Add(tic);
}
}
}
HttpContext.Current.Session["cart"] = cart;
return result;
} /// <summary>
/// 从购物车中移除商品
/// </summary>
/// <param name="tic">要移除的商品ID</param>
/// <returns></returns>
public static int removeCart(string tid)
{
shoppingCart cart = getShoppingCart();
if (cart.CategoryID == )
{
//离开太久啦,购物车已经空空了,您重新购买吧
return -;
}
else
{
ticket t1 = cart.tickets.SingleOrDefault(obj => obj.ticketID == tid);
if (t1 != null)
{
//重新计算总价
cart.TotalPrice -= t1.ticketPrice * t1.ticketCount;
//从购物车中移除
cart.tickets.Remove(t1);
}
}
HttpContext.Current.Session["cart"] = cart;
return ;
} /// <summary>
/// 减少购物车中某一商品的数量
/// </summary>
/// <param name="tic">要减少数量的商品id</param>
/// <returns></returns>
public static int reduceCart(string tid)
{
shoppingCart cart = getShoppingCart();
if (cart.CategoryID == )
{
//离开太久啦,购物车已经空空了,您重新购买吧
return -;
}
else
{
ticket t1 = cart.tickets.SingleOrDefault(obj => obj.ticketID == tid);
if (t1 != null)
{
if (t1.ticketCount > )
{
//从购物车中减少某一商品的数量
t1.ticketCount--;
//重新计算总价
cart.TotalPrice -= t1.ticketPrice;
}
}
}
HttpContext.Current.Session["cart"] = cart;
return ;
} /// <summary>
/// 增加购物车中某一商品的数量
/// </summary>
/// <param name="tic">要减少数量的商品id</param>
/// <returns></returns>
public static int addCart(string tid)
{
shoppingCart cart = getShoppingCart();
if (cart.CategoryID == )
{
//离开太久啦,购物车已经空空了,您重新购买吧
return -;
}
else
{
ticket t1 = cart.tickets.SingleOrDefault(obj => obj.ticketID == tid);
if (t1 != null)
{
if (t1.ticketCount < )
{
//从购物车中减少某一商品的数量
t1.ticketCount++;
//重新计算总价
cart.TotalPrice += t1.ticketPrice;
}
}
}
HttpContext.Current.Session["cart"] = cart;
return ;
}
}
/// <summary>
/// 购物车
/// </summary>
public class shoppingCart
{
/// <summary>
/// 门票类别ID
/// </summary>
public int CategoryID { get; set; }
/// <summary>
/// 总价
/// </summary>
public decimal? TotalPrice { get; set; }
/// <summary>
/// 门票列表
/// </summary>
public List<ticket> tickets { get; set; }
}
/// <summary>
/// 门票
/// </summary>
public class ticket
{
public string ticketID { get; set; }
/// <summary>
/// 门票名称
/// </summary>
public string ticketName { get; set; }
/// <summary>
/// 门票数量
/// </summary>
public int ticketCount { get; set; }
/// <summary>
/// 门票价格
/// </summary>
public decimal? ticketPrice { get; set; }
}
}
购物车类
方法二:在方法上加[Webservice],方法必须是静态,static
后台:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services; namespace WebApplication1.BookManage
{
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ } [WebMethod]
public static string SayHello(string str,string str2)
{
return str+str2;
}
}
}
1
前台:
Js中:
$(function () {
$("#btnOK").click(function () {
$.ajax({
type: "post",
url: "test.aspx/SayHello",
data: "{'str':'我是','str2':'XXX'}",
contentType: "application/json",
dataType: "json",
success: function (r) {
alert(r.d);
},
error: function (e) {
alert("错误是:" + e.responseText);
}
});
return false;
});
}) 界面:
<form id="form1" runat="server">
<input type="button" value="调用后台方法" id="btnOK"/>
</form>
2
方法三:一般处理程序
前台:
JS:
function strToJson(str) {
var json = eval('(' + str + ')');
return json;
}
$("#btnone").click(function () {
$.ajax({
type:"post",
url: "/Ajax_Data/Handler.ashx",
data: {method:"a"},
dataType: "text",
success: function (r) {
var obj = strToJson(r);
alert(obj.name+" "+obj.age);
},
error: function (e) {
alert("错误:"+e.responseText);
}
});
}); 界面:
<input type="button" value="使用一般处理程序调用后台" id="btnone" />
one
后台:
/// <summary>
/// Handler 的摘要说明
/// </summary>
public class Handler : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
char charmehod = Convert.ToChar(context.Request.Params["method"]);
context.Response.ContentType = "text/plain"; switch (charmehod)
{
case 'a':
context.Response.Write("{name:'魔女小溪',age:'22' }");
break;
case 'b':
context.Response.Write("document.write(\"This is b samply\");");
break;
default:
break;
}
context.Response.Flush(); } public bool IsReusable
{
get
{
return false;
}
}
}
two