利用AjaxPro2实现商品属性选择(C#

1、准备:下载AjaxPro.2.dll

2、应用:项目中引用AjaxPro.2.dll

3web.config中引用:

[plain] view plain copy
  1. <system.web>
  2. <httpHandlers>
  3. <addverb="*"path="*.ashx"type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
  4. </httpHandlers>
  5. </system.web>

4、如果部署在windows server 2008 + IIS 7.0中,还需要在web.config<system.webServer>节点中配置以下信息:

[csharp] view plain copy
  1. <!--程序部署在windowsserver2008+IIS7.0,需要在此处声明AjaxPro2,才能正常使用-->
  2. <system.webServer>
  3. <handlers>
  4. <addname="ajaxpro"verb="*"path="*.ashx"type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
  5. </handlers>
  6. </system.webServer>

5前台代码

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="shopDetail.aspx.cs" Inherits="shopDetail" %>

<!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">
<Meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
<Meta charset="utf-8"> 
<title>宝贝详情</title> 
<Meta content="yes" name="apple-mobile-web-app-capable">
 <Meta content="black" name="apple-mobile-web-app-status-bar-style"> 
 <Meta name="format-detection" content="telephone=no"> 
 <style>
    .liselect a
    {
        border: 2px solid #DF0001;
        Box-shadow: 1px 1px 3px 0 rgba(0,0.6);
        margin: -1px;
    }
</style>
  <Meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
  <link rel="stylesheet" type="text/css" href="css/index-black.css" />
  <style type="text/css">
img {width:expression(this.width>300?"300px":this.width+"px");}
</style>

<%--引入JQuery框架--%>
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
 

<!--//商品属性选择 jQuery-->
<script type="text/javascript">
var imgmultbf="";//多图备份
$(document).ready(function(){

$(".product_size").mouSEOut(function(){ $(this).removeAttr("style"); })
$(".product_size").mouSEOver(function(){$(".product_size").attr("style","border:1px solid #fcbb29;background:#FFF3D9;")});

$(".restrict ul li").not(".litit").each(function(i){ $(this).click(function()
{ 
    
   $(this).siblings().not(".litit").children("img").remove();
   $(this).siblings().not(".litit").removeAttr("class");
   $(this).attr("class","liselect");
   $(this).append($("<img class=\"sico\" src=\"Images/ii1.gif\" />"));
   $("#divnoSelect").hide();
   $("#divSelect").show();
   var spenames="";
   var isselect=0; //规格选择的个数
   var prodspec="";//选择的规格值(所有已勾选的规格值)
   var Nowprodspec="";//当前选择的规格值
   var prodguid=$("#HiddenFieldGuid").val();  //商品guid
   var memloginid=$("#HiddenFieldMemloginID").val();//会员loginid
   if(imgmultbf=="")
   {
    imgmultbf=$("#tb_gallery").html();//多图备份
    }
   //开始处理多图(使用getJson+ashx方式实现数据交互,但ajaxPro2与getJson不能同时使用)
     Nowprodspec=$(this).attr("spc");
     params = {"prodguid":prodguid,"yz":"shopnum1ntbl","loginid":memloginid,"spec":Nowprodspec,"type":"img"}; 
      $.getJSON("/Api/shopproductspec.ashx",params,function(json){
     
             if(json[0].imgsrc!=null)
             {
           //绑定选择规格后的大图
            $("#ProductDetail_ctl00_RepeaterData_ctl00_Productimgurl").attr("src",""+json[0].imgsrc+"");
            $("#ProductDetail_ctl00_RepeaterData_ctl00_Productimgurl").attr("jqimg",""+json[0].imgsrc.replace("s_","")+"");
            //绑定属性缩略图
            $(".list-h li").remove();
            
            
$.each(json,function(i) {
 if(json[i].imgsrc!="")
    {
    $(".list-h").append($("<li class=\"tb_diply\"></li>").append($("<div class=\"tb-pic tb-stn\"></div>").append($("<a></a>").append($("<img />").attr("src",json[i].imgsrc)))))
    }
});
    //给缩略图加宽度
           var width_l=parseInt(json.length)*60;
//           $(".list-h").attr("style","");		
//				  $(".list-h").css({
//						"width":""+width_l+"px"
//					});
             }
             else
             {
  
              $("#tb_gallery").html(imgmultbf);

             }
				$("#tb_gallery img").bind("mouSEOver",function(){
					var src=$(this).attr("src");
					$("#spec-n1 img").eq(0).attr({
						src:src.replace("\/n5\/","\/n1\/"),jqimg:src.replace("\/n5\/","\/n0\/")
					});
					$(this).parent().parent().parent().addClass("tb_selected");
				}).bind("mouSEOut",function(){
		            $(this).parent().parent().parent().removeClass("tb_selected");
				});	
             });
   //处理多图结束
   //开始处理其它效果
   var juls=$(".restrict ul")  
    juls.each(function(i){
if($(this).children("li").hasClass("liselect"))
        {
           isselect++;
           spenames+="\""+$(this).children(".liselect").find("span").html()+"\""+"  ";
           prodspec=prodspec+$(this).children(".liselect").attr("spc")+";";
           
           // 添加的
           document.getElementById('<%=HiddenFieldGuiGe.ClientID %>').value=prodspec;
           
         }
  
     });
     $("#divSelect .selected").html(spenames);  //选择了  
     
    //开始处理商品价格、库存
    if(juls.length==isselect)
    {
      //方法一:使用ajax,开始调用后台方法 
     //alert(document.getElementById('<%=HiddenFieldGuiGe.ClientID %>').value);
     prodspec=prodspec.substring(0,prodspec.length-1);
     var refs=shopDetail.GetProductInfoByDetail(prodguid,prodspec).value;
     if(refs!="0")
     {
       var val=refs.split('$$$');
       document.getElementById("LabelShopPrice").innerHTML=val[0];
       document.getElementById("LabelRepertoryCount").innerHTML=val[1];
     }
    
     }
     
     //方法二:使用getJson+ashx,待定(ajaxPro2与jQuery不能共用,在web.config中声明了ajaxPro2,getJson+ashx不起作用)
     
     
     });})});

function  checkSubmit()  //检查数量
{
 ///检查库存
 var buyNum=document.getElementById("<%=TextBoxBuyNum.ClientID %>").value;
 var numyz=/^[0-9]{1,9}$/;
if(!numyz.exec(buyNum))
{
   alert("购买数量格式不正确!")
   document.getElementById("<%=TextBoxBuyNum.ClientID %>").get(0).focus();
   return false;
}

 var allcout=$("#LabelRepertoryCount").text();
 if(parseInt(buyNum)>=parseInt(allcout))
 {
   alert("库存不足!")
   return false;
 }
 
 //检查规格
// var juls=$(".restrict ul")  
var juls=$(".restrict ul")  
 var spenames="";
    juls.each(function(i){
     if($(this).children(".liselect").length==0)
     {

       spenames+="\""+$.trim($(this).children(":first-child").find("span").text())+"\""+" ";
     }
  
     });
 if(spenames!="")
 {
   alert("请选择  "+spenames);
   return false;
 }
 
}

</script>


<!--购买数量加减-->

<script type="text/javascript">

//加
function AddNum()
{
   var BuyNum=parseInt(document.getElementById("<%=TextBoxBuyNum.ClientID %>").value);
   document.getElementById("<%=TextBoxBuyNum.ClientID %>").value=BuyNum+1;
}

function SubNum()
{
   var BuyNum=parseInt(document.getElementById("<%=TextBoxBuyNum.ClientID %>").value);
   if(BuyNum>1)
   {
   document.getElementById("<%=TextBoxBuyNum.ClientID %>").value=BuyNum-1;
   }
}
</script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
     <div class="viewport enableNavbar enabletoolbar enableTransition"> 
 <header class="navbar">
 <ul><li>商品详情</li><li>
 <a class="c-btn c-btn-aw" data-id="btn-1387959379238" href="javascript:history.go(-1);"><span>返回</span></a></li>
 <li></li></ul>
 </header>
  <section class="content" style="min-height: 451px;">
  <div class="wrap"><div class="inactive prev" index="0">
  </div>
  <div class="active" index="1" data-fragment="" style="min-height: 451px;">
  <div id="J_detail" style="min-height: 451px;">
  <div id="J_detail_main">
  <div class="dt-slider">
  <div class="dt-slider-cont" style="width: 354px; -webkit-transform: translateZ(0px);"> 
  <ul class="dt-slct-ul" style="-webkit-transform: translate3d(0px,0px,0px); -webkit-backface-visibility: hidden; width: 1416px;"> 
  
   <li style="width:354px" l="1"> 
	<img class="" src="http://localhost:8011<%=pPic%>"> 
	</li> 
	 </ul> 
	 <div class="dt-slider-mask"></div> </div> 
	 <%--<div class="dt-slider-status">  
	 <i class="sel"></i>  <i></i>  <i></i>  <i></i> 
	  </div>--%>
	   <ul class="dts-ul">  <li class="dts-fav"><a href="?type=fav&guid=<%=Guid %>">收藏</a></li> 
	   <li class="dts-faved">已收藏</li> 
	    </ul> </div>
	    <div class="dt-info"><h1 class="dtif-h"><%=pName%></h1> 

	    <ul>  <li class="dtif-p1"> 
	     <ins class="orange">¥<%--<%=sPrice %>--%>
	     <asp:Label ID="LabelShopPrice" runat="server"></asp:Label>
	     </ins><br> <span class="lgray dtif-ps1"><del>¥<%=mPrice %></del></span>   </li>  
	      <li class="dtif-p2 bt lgray"> 
	      <span class="dtifp-l">  库存: 
	      <asp:Label ID="LabelRepertoryCount" CssClass="storage" runat="server"></asp:Label>
                                        <asp:Label ID="Label2" runat="server"></asp:Label> </span> 
	      <%--<span  width=35px>已售<%=saleNum %>笔</span> --%>
	      <span class="dtifp-r">数量:</span>
	      <span  width=100px><span class="decrease" onclick="SubNum();"></span><asp:TextBox ID="TextBoxBuyNum" CssClass="amount_widget" runat="server" Text="1" />
           <span class="increase" onclick="AddNum();"></span>
           <%--<asp:Label ID="LabelUnit" runat="server" Text='<%# ((DaTarowView)Container.DataItem).Row["UnitName"] %>'></asp:Label>--%></span> 
	        </li>
	     <li class="dtif-p2 bt lgray"> 
	      <span class="dtifp-l">  <%=GetFeeByProGuid()%>  </span> 
	      <span  width=35px>已售<%=saleNum %>笔</span> 
	      <span class="dtifp-r"><%=address %></span>  </li>  </ul> 
	      
	     </div>

	 <!--商品规格 20140415-->
	 <asp:HiddenField ID="HiddenFieldGuiGe" runat="server" Value="0"></asp:HiddenField>
	  <div class="restrict" id="divShopSpec" runat="server" visible="false" >
           <asp:Repeater ID="RepeaterProductSepc" runat="server" EnableViewState="false" OnItemDataBound="RepeaterProductSepc_ItemDataBound">
                                                <ItemTemplate>
                                                    <dl class="tb_prop clearfix">
                                                        <dt>
                                                            <%#((System.Data.DaTarowView)Container.DataItem).Row["SpecificationName"]%>:</dt>
                                                        <dd>
                                                            <ul>
                                                                <asp:Repeater ID="RepeaterProductSepcDetail" runat="server" EnableViewState="false">
                                                                    <ItemTemplate>
                                                                        <li spc='<%#((System.Data.DaTarowView)Container.DataItem).Row["SpecDetail"]%>'><a href="javascript:void(0)">
                                                                       <%-- <a href="javascript:View()">--%>
                                                                            <span>
                                                                                <%#((System.Data.DaTarowView)Container.DataItem).Row["isImage"].ToString() == "True" ? "<img src='/ImgUpload/" + ((System.Data.DaTarowView)Container.DataItem).Row["Image"] + "' width=\"40\" height=\"16\" />" : ((System.Data.DaTarowView)Container.DataItem).Row["Name"]%></span></a></li>
                                                                    </ItemTemplate>
                                                                </asp:Repeater>
                                                            </ul>
                                                        </dd>
                                                    </dl>
                                                </ItemTemplate>
                                                <FooterTemplate>
                                                    <div id="divnoSelect" style="clear: both; padding-top: 6px; padding-top: 0px\9;">
                                                        <span style="font-weight: bold; clear: both;">请选择</span>:<span id="spanNoSelect"
                                                            style="font-weight: bold; clear: both;" runat="server"><asp:Label ID="lblSpecName" runat="server" ></asp:Label> </span>
                                                    </div>
                                                    <div id="divSelect" style="clear: both; display: none;">
                                                        <span style="font-weight: bold; clear: both;">已选择</span>:<span class="selected"></span></div>
                                                    </div>
                                                </FooterTemplate>
                                            </asp:Repeater>
                                        </div>
               <div class="dt-action"> <div class="dta-iner">  
            
 </div></div>

 </div>
 </div></div></div><div class="inactive next" index="2"></div><div class="inactive" index="3"></div><div class="inactive" index="4"></div>
     </div><div class="trans"><div></div></div></section>  </div> 
     

<asp:HiddenField ID="HiddenFieldGuid" runat="server" Value="0" />
<asp:HiddenField ID="HiddenFieldMemloginID" runat="server" Value="0" />
    </form>
</body>
</html>

6、后台代码

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using mshopClass;
using ShopNum1.Common;
using System.Data.sqlClient;

public partial class shopDetail : System.Web.UI.Page
{
    public string Guid = "";
    protected void Page_Load(object sender,EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["guid"] != "" && Request.QueryString["guid"] != null)
            {
                BindShopDetail(Request.QueryString["guid"]);
                BindSpecification(Request.QueryString["guid"]);  //绑定规格属性,2014-04-15
                Guid = Request.QueryString["guid"];
            }
        }
        //引入ajax(处理前后台数据交换),2014-04-15
        AjaxPro.Utility.RegisterTypeForAjax(typeof(shopDetail));
    }


    #region 商品属性
    public string pName = "";  //商品名称
    public string pPic = "";   //商品图片
    public string sPrice = "";  //商城价格
    public string mPrice = "";  //市场价格
    public string saleNum = "";  //已售数量
    public string memLoginID = "";  //商品所属卖家
    public string shopContent = "";   //商品内容
    public string shopNum = "";  //库存
    public string unitName = "";  //单位
    #endregion


    //绑定商品详细信息
    void BindShopDetail(string Guid)
    {
        string sql = "select  *,originalImage2=replace(originalImage,'~',''),ThumbImage2=replace(ThumbImage,'') from tb1_Shop_Product where guid='" + Guid + "'";
        DataTable dt = mallCtr.sqlTable(sql);
        if (dt.Rows.Count > 0)
        {
            pName = dt.Rows[0]["name"].ToString();
            pPic = dt.Rows[0]["originalImage2"].ToString();
            sPrice = dt.Rows[0]["shopprice"].ToString();
            LabelShopPrice.Text = dt.Rows[0]["shopprice"].ToString();  //2014-04-15
            mPrice = dt.Rows[0]["marketprice"].ToString();
            saleNum = dt.Rows[0]["saleNumber"].ToString();
            memLoginID = dt.Rows[0]["memLoginID"].ToString();
            shopContent = Server.HtmlDecode(dt.Rows[0]["detail"].ToString());
            shopNum = dt.Rows[0]["RepertoryCount"].ToString();
            LabelRepertoryCount.Text = shopNum;
            unitName = dt.Rows[0]["unitName"].ToString();
            Label2.Text = unitName;
            HiddenFieldGuid.Value = dt.Rows[0]["guid"].ToString();
            HiddenFieldMemloginID.Value = memLoginID;
            //lblDetail.Text = Server.HtmlDecode(dt.Rows[0]["detail"].ToString());
            lblInstruction.Text = Server.HtmlDecode(dt.Rows[0]["Instruction"].ToString());
        }
    }


    #region 绑定商品规格属性 20140415
    void BindSpecification(string Guid)
    {
        //判断该商品是否有属性规格
        string sql = "select * from tb1_SpecificationProudct where productGuid='" + Guid + "'";
        DataTable sdt = mallCtr.sqlTable(sql);
        if (sdt.Rows.Count > 0)   //该商品有属性规格
        {
            divShopSpec.Visible = true; //显示商品属性规格

            sql = "select p.guid,p.productCategoryCode,c.id,pc.specificationID,sguid=s.guid,s.specificationName from tb1_Shop_Product p " +
                   " left join tb1_ProductCategory c on p.productCategoryCode=c.code " +
                   " inner join tb1_SpecificationProudctCategory pc on pc.productCategoryID=c.id " +
                   " left join tb1_SpecificationManagement s on s.guid=pc.specificationID " +
                   "where p.guid='" + Guid + "'";
            DataTable dt = mallCtr.sqlTable(sql);
            if (dt.Rows.Count > 0)
            {
                RepeaterProductSepc.DataSource = dt;
                RepeaterProductSepc.DataBind();

                //请选择规格
                string nameSel = "";
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    nameSel += "\"" + dt.Rows[i]["specificationName"].ToString() + "\" ";
                }


                Label lblSpecName = ((Label)RepeaterProductSepc.Controls[RepeaterProductSepc.Controls.Count - 1].FindControl("lblSpecName"));

                if (nameSel.Length > 0)
                {
                    lblSpecName.Text = nameSel.Substring(0,nameSel.Length - 1);
                }
                //lblSpecName.Text = nameSel.Substring(0,nameSel.Length - 1);
                //spanNoSelect = nameSel.Substring(0,nameSel.Length - 1);   

            }
        }
        else
        {
            divShopSpec.Visible = false; //显示商品属性规格
        }
    }

    protected void RepeaterProductSepc_ItemDataBound(object sender,System.Web.UI.WebControls.RepeaterItemEventArgs e)
    {

        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            //找到分类Repeater关联的数据项 
            DaTarowView rowv = (DaTarowView)e.Item.DataItem;
            //提取分类ID 
            string spcid = Convert.ToString(rowv["sguid"]);

            //获取规格详细属性
            DataTable sdt = BindSpecInfo(Request.QueryString["guid"],spcid);

            if (sdt.Rows.Count > 0)
            {
                Repeater RepeaterProductSepcDetail = (Repeater)e.Item.FindControl("RepeaterProductSepcDetail");
                RepeaterProductSepcDetail.DataSource = sdt;
                RepeaterProductSepcDetail.DataBind();
            }
        }
    }

    //获取规格详细信息(查找商品规格关系表(自建表))
    private DataTable BindSpecInfo(string guid,string sid)
    {
        string sql = "select guid,productGuid,specificationGuid,specDetailGuid,name=specDetailName,SpecDetail=detail,image,isimage from tb1_SpecificationProudct2 " +
                   " where productGuid='" + guid  + "' and specificationGuid=" + sid ;
        return mallCtr.sqlTable(sql);
    }


    //根据传递过来的商品规格获取商品信息(引入ajax)
    [AjaxPro.AjaxMethod]
    public string GetProductInfoByDetail(string guid,string detail)
    {
        string refs = "0";
        if (detail != "")
        {
            string price = "";
            string proNum = "";
            string sql = "select * from tb1_SpecificationProudct where productGuid='" + guid + "' and detail='" + detail + "'";
            DataTable dt = mallCtr.sqlTable(sql);
            if (dt.Rows.Count > 0)
            {
                price = dt.Rows[0]["price"].ToString();
                proNum = dt.Rows[0]["RepertoryCount"].ToString();
                refs = price + "$$$" + proNum;
            }
        }
        return refs;
    }

    #endregion

}


效果

1、未选择前:



2、选择“黑色”、“L”



3、选择“白色”、“M”




实例下载:利用AjaxPro2实现商品属性选择实例下载

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...