利用AjaxPro2實現商品屬性選擇(C#)

1、準備:下載AjaxPro.2.dll

2、應用:項目中引用AjaxPro.2.dll

3web.config中引用:

[plain] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <system.web>  
  2. <httpHandlers>  
  3.    <add verb="*" 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 plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <!--程序部署在windows server 2008+IIS7.0,需要在此處聲明AjaxPro2,才能正常使用-->  
  2.   <system.webServer>  
  3.     <handlers>  
  4.       <add name="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, 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" οnclick="SubNum();"></span><asp:TextBox ID="TextBoxBuyNum" CssClass="amount_widget" runat="server" Text="1" />
           <span class="increase" οnclick="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實現商品屬性選擇實例下載



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章