未使用!Page.IsPostBack出现的错误

本文通过一个实际案例说明了在ASP.NET中Page.IsPostBack判断的重要性。作者在不使用此判断的情况下遇到了数据无法正确更新的问题,最终通过加入NotPage.IsPostBack解决了问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

未使用Not Page.IsPostBack出现的错误

                                      

 

今天用.net调试一个程序,由于时间比较仓促,在所有的页面page_load中未加Not Page.IsPostBack 的判断语句,开始我并未在意,在一个数据更新页面,我试着先在page_load中从数据库读取数据到TextBox中,运行后一切显示正常,但是我一点更新按钮,怪事出现了,虽然Textbox中的数据我刚刚已经修改过了,但是更新后,出现的还是老数据,我试着把textbox中的数据用response.write打印出来,结果显示的是未修改前的数据,我花了很长时间也没有找出错误的原因,最后,我想是不是页面在回送时textbox中的数据被page_load事件还原了,于是我加了一个Not Page.IsPostBack的判断语句,结果更新成功了,于是我思考,button按钮触发时先积习发生的是page_load,然后才是click事件,唉,又长一智!

根据代码帮忙了解,GCCode是怎么获取到的 using System; using System.Collections.Generic; using System.Data; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Ymycc.ComUtility; using Ymycc.Wis.Model; using Ymycc.Wis.Com; using Ymycc.Wis.Bll; using Ymycc.Wis.Biz.Bll; using Ymycc.Wis.Biz.Model; using System.Threading; using System.EnterpriseServices; public partial class Bk_Rep_TopACList : WisPage { BlUser blUsr = new BlUser(); BlBizInfo blInfo = new BlBizInfo(); ExpBkOpr expBkOpr = new ExpBkOpr(); protected void Page_Load(object sender, EventArgs e) { lb_Notes.Text = ""; bool runRep = true; DataTable dataTB = null; UserInfo lUser = UserOpr.LogonUser; BlDataMap dco = new BlDataMap(); //tb_VoyageCode.Text = "AW3236E"; tb_VpEtdFrom.Attributes.Add("onclick", "SelectDate(this,'yyyy-MM-dd',0,0)"); tb_VpEtdTo.Attributes.Add("onclick", "SelectDate(this,'yyyy-MM-dd',0,0)"); string bkOfsIn = tb_bkOfsIn.UpcText?.Trim(); string tradeCode = tb_Trade.Text.Trim().ToUpper(); string wk = tb_wk.Text.Trim(); string cmsCode = tb_CustCode.Text.Trim(); string cmsCodeOn = tb_CustCodeOn.Text.Trim(); string GcCode = tb_GCCode.Text.Trim();//GCCode string voyageCodes = tb_VoyageCode.Text.Trim(); string allocVoyCodes = tb_AllocVoy.Text.Trim(); string loadPortCode = tb_LoadPort.Text.Trim(); string dischPortCode = tb_DischPort.Text.Trim(); string finalLocCode = tb_FinalLoc.Text.Trim(); string vpEtdFrom = tb_VpEtdFrom.Text.Trim(); string vpEtdTo = tb_VpEtdTo.Text.Trim(); string caseIDs = tb_CaseIDs.Text.Trim(); string ctrTypes = tb_CtrTypes.Text.Trim(); string pc = ddl_Freight.SelectedValue.Trim(); string ft = "<b>TOP A/C LIST</b>"; ft += bkOfsIn == "" ? "" : (", <b>Bk Office:</b> " + bkOfsIn); ft += voyageCodes == "" ? "" : (", <b>Voyage:</b> " + voyageCodes.ToUpper()); ft += allocVoyCodes == "" ? "" : (", <b>Alloc Voyage:</b> " + allocVoyCodes.ToUpper()); ft += tradeCode == "" ? "" : (", <b>Trade:</b> " + tradeCode.ToUpper()); ft += loadPortCode == "" ? "" : (", <b>LoadPort:</b> " + loadPortCode.ToUpper()); ft += dischPortCode == "" ? "" : (", <b>DischPort:</b> " + dischPortCode.ToUpper()); ft += finalLocCode == "" ? "" : (", <b>FinalLoc:</b> " + finalLocCode.ToUpper()); ft += cmsCode == "" ? "" : (", <b>CustCode:</b> " + cmsCode.ToUpper()); ft += cmsCodeOn == "" ? "" : (", <b>OnCustCode:</b> " + cmsCodeOn.ToUpper()); ft += GcCode == "" ? "" : (", <b>GC Code:</b> " + GcCode.ToUpper());//GCCode ft += vpEtdFrom == "" ? "" : (", <b>ETD From:</b> " + vpEtdFrom); ft += vpEtdTo == "" ? "" : (", <b>To</b> " + vpEtdTo); ft += caseIDs == "" ? "" : (", <b>CaseID:</b> " + caseIDs.ToUpper()); ft += ctrTypes == "" ? "" : (", <b>CtrType:</b> " + ctrTypes.ToUpper()); ft += pc == "" ? "" : (", <b>P/C:</b> " + pc.ToUpper()); List<string> voyages = new List<string>(); if (!Page.IsPostBack) { tb_bkOfsIn.UpcText = lUser.UserOffice?.OfficeCode; //tb_bkOfs.Text = lUser.UserOffice?.OfficeCode; //userOpr.BindUserBizAcsOfsToDDL(ddl_bkOfs, lUser.UserOffice.OfficeCode, false, true, ""); string upfs = blUsr.GetUserPreference(lUser.UserKey, "BK_REP_TOPACLIST"); foreach (ListItem li in this.cbl_ShowFields.Items) { if (upfs.IndexOf(li.Value) >= 0) { li.Selected = true; } } } else { try { if (voyageCodes == "") { if (vpEtdFrom == "" || vpEtdTo == "") { if (wk == "" || tradeCode == "") { throw new Exception("ETD时间范围或者周期,两者必须输入其一!"); } } } if (wk != "" & tradeCode != "") { if (tradeCode == "NCP") { voyageCodes = dco.GetMatched("EXP_BK_EU_WEEKVOY", lUser.UserOffice.OfficeCode, new DataMapParam(DmmField.C0, wk)) + "," + voyageCodes; } if (tradeCode == "MED") { voyageCodes = dco.GetMatched("EXP_BK_MED_WEEKVOY", lUser.UserOffice.OfficeCode, new DataMapParam(DmmField.C0, wk)) + "," + voyageCodes; } } if (vpEtdFrom != "" || vpEtdTo != "") DateTimeHelper.CheckFromToDateTime(ref vpEtdFrom, ref vpEtdTo, "MM", 3); if (voyageCodes != "") { voyageCodes = voyageCodes.Replace(",", ",").Replace(";", ",").Replace(";", ",").TrimEnd(','); foreach (string s in voyageCodes.Split(',')) { voyages.Add(s.Trim()); } } else { string PortList = blInfo.GetOfsVPorts(lUser.UserOffice.OfficeCode); if (string.IsNullOrEmpty(PortList) && !string.IsNullOrEmpty(bkOfsIn))//订舱地不为空且PortList为空 { PortList = blInfo.GetLocByAolOffice(bkOfsIn); } else if (string.IsNullOrEmpty(PortList)) { PortList = string.Empty; } voyages = blInfo.GetVoyagesByvpPorts(PortList, vpEtdFrom, vpEtdTo + " 23:59:59"); } string f = "1=1 "; //if (!string.IsNullOrEmpty(bkOfs)) { // f += " and BkOffice = '" + bkOfs + "'"; //} if (!string.IsNullOrEmpty(loadPortCode)) { f += " and LoadPortCode in ('" + loadPortCode.Replace(",", ",").Replace(",", "','") + "')"; } if (!string.IsNullOrEmpty(dischPortCode)) { f += " and DischPortCode in ('" + dischPortCode.Replace(",", ",").Replace(",", "','") + "')"; } if (!string.IsNullOrEmpty(finalLocCode)) { f += " and FinalLocCode in ('" + finalLocCode.Replace(",", ",").Replace(",", "','") + "')"; } if (!string.IsNullOrEmpty(tradeCode)) { f += " and TradeCode in ('" + tradeCode.Replace(",", ",").Replace(",", "','") + "')"; } if (!string.IsNullOrEmpty(caseIDs)) { f += " and CaseID in ('" + caseIDs.Replace(",", ",").Replace(",", "','") + "')"; } if (!string.IsNullOrEmpty(cmsCode)) { f += " and CustCode in ('" + cmsCode.Replace(",", ",").Replace(",", "','") + "')"; } if (!string.IsNullOrEmpty(cmsCodeOn)) { f += " and OnCustCode in ('" + cmsCodeOn.Replace(",", ",").Replace(",", "','") + "')"; } if (!string.IsNullOrEmpty(GcCode)) { f += " and GCCode in ('" + GcCode.Replace(",", ",").Replace(",", "','") + "')";//GCCode } if (!string.IsNullOrEmpty(pc)) { f += " and FreightMode in ('" + pc.Replace(",", ",").Replace(",", "','") + "')"; } if (!string.IsNullOrEmpty(allocVoyCodes)) { f += " and AllocVoyage in ('" + allocVoyCodes.Replace(",", ",").Replace(",", "','") + "')"; } string cf = ""; string[] qcArray = null; ctrTypes = ctrTypes.ToUpper().Replace(",", ",").Replace(";", ",").Replace(";", ","); if (ctrTypes != "") { qcArray = ctrTypes.Split(','); foreach (string c in qcArray) { cf += cf == "" ? ("CtrType='" + c + "'") : (" or CtrType='" + c + "'"); } } if (cf != "") f += " and (" + cf + ")"; CargoFields[] qFields = new CargoFields[] { CargoFields.BkOffice, CargoFields.CustCode, CargoFields.CustName, CargoFields.OnCustCode, CargoFields.OnCustName, CargoFields.TradeCode,CargoFields.LoadVoyage, CargoFields.CaseID, CargoFields.CaseIDHolder,CargoFields.GCCode, CargoFields.LoadPortCode, CargoFields.DischPortCode, CargoFields.FinalLocCode, CargoFields.PreCarriageVoyage, CargoFields.AllocVoyage, CargoFields.CtrKey, CargoFields.CtrType, CargoFields.CtrTeu, CargoFields.CtrSize, CargoFields.EirPrinted, CargoFields.FreightMode }; foreach (string v in voyages) { CargoQueryParam cqp = new CargoQueryParam(); cqp.LoadVoyage = v; cqp.BkStatus = "P"; //cqp.CustCode = cmsCode; //cqp.OnCustCode = cmsCodeOn; cqp.BkOfficeIn = bkOfsIn == "" ? lUser.UserOffice?.OfficeCode : bkOfsIn; DataTable d = expBkOpr.PRSelect(cqp, qFields); if (d != null && d.Rows.Count > 0) { if (dataTB == null) { dataTB = d.Clone(); } foreach (DataRow dr in d.Select(f)) { dataTB.Rows.Add(dr.ItemArray); } } Thread.Sleep(20); } } catch (Exception ex) { runRep = false; WriteTxtLog.WriteLog_ExceptionNotes("Bk_ReportGen_TopAccountList: err:" + ex.ToString()); lb_Notes.Text = "<font color='red'>出现错误:</font>" + ex.Message; } //rep control: Dictionary<string, string> udfFieldsTitle = new Dictionary<string, string>(); udfFieldsTitle.Add("BkOffice", "OFFICE"); udfFieldsTitle.Add("PRECARRIAGEVOYAGE", "PRECARRIAGE"); udfFieldsTitle.Add("LOADPORTCODE", "LOADPORT"); udfFieldsTitle.Add("DISCHPORTCODE", "DISCHPORT"); udfFieldsTitle.Add("FINALLOCCODE", "FINALLOC"); List<string> topFields = new List<string>(); topFields.Add(CargoFields.LoadVoyage.ToString()); //topFields.Add(CargoFields.LoadPortCode.ToString()); //topFields.Add(CargoFields.DischPortCode.ToString()); List<string> leftFields = new List<string>(); leftFields.Add(CargoFields.CustCode.ToString()); leftFields.Add(CargoFields.CustName.ToString()); bool showEIR = false; string upfs = ""; //根据栏位选择 foreach (ListItem li in this.cbl_ShowFields.Items) { if (li.Selected) { switch (li.Value.ToString().Trim()) { case "BkOfs": leftFields.Insert(0, CargoFields.BkOffice.ToString()); break; case "OnCust": { leftFields.Add(CargoFields.OnCustCode.ToString()); leftFields.Add(CargoFields.OnCustName.ToString()); }; break; case "CaseID": leftFields.Add(CargoFields.CaseID.ToString()); break; case "CaseIDHdr": leftFields.Add(CargoFields.CaseIDHolder.ToString()); break; case "GCCode": leftFields.Add(CargoFields.GCCode.ToString()); break;//GCCode case "PreCarriage": leftFields.Add(CargoFields.PreCarriageVoyage.ToString()); break; case "AllocVoy": leftFields.Add(CargoFields.AllocVoyage.ToString()); break; case "LoadPort": leftFields.Add(CargoFields.LoadPortCode.ToString()); break; case "DischPort": leftFields.Add(CargoFields.DischPortCode.ToString()); break; case "FinalLoc": leftFields.Add(CargoFields.FinalLocCode.ToString()); break; case "EIR": showEIR = true; break; default: break; } upfs += (upfs == "" ? "" : ",") + li.Value?.Trim(); } } blUsr.SetUserPreference(lUser.UserKey, "BK_REP_TOPACLIST", upfs); string topSort = CargoFields.CustCode.ToString(); string lefSort = ""; List<string> topTTLFields = new List<string>(); List<string> leftTTLFields = new List<string>(); //leftTTLFields.Add("LoadVoyage"); //leftTTLFields.Add("BkOffice"); Dictionary<string, List<string>> udfTopFldVals = new Dictionary<string, List<string>>(); //udfTopFldVals.Add("dischportcode", new string[] { "MYPKE", "IRBAB", "IQUQR", "AEJEA" }); Dictionary<string, List<string>> udfLeftFldVals = new Dictionary<string, List<string>>(); //udfLeftFldVals.Add("BkOffice", new string[] { "SHA", "NGB", "XMN", "DLC" }); Dictionary<string, Dictionary<string, string>> spcFld = new Dictionary<string, Dictionary<string, string>>(); Dictionary<string, string> c20 = new Dictionary<string, string>(); c20.Add("C", "count(CtrKey)"); c20.Add("F", "CtrSize = '20'"); spcFld.Add("20'", c20); Dictionary<string, string> c40 = new Dictionary<string, string>(); c40.Add("C", "count(CtrKey)"); c40.Add("F", "CtrSize = '40' and CtrType <> '40HQ'"); spcFld.Add("40'", c40); Dictionary<string, string> c40HQ = new Dictionary<string, string>(); c40HQ.Add("C", "count(CtrKey)"); c40HQ.Add("F", "CtrType = '40HQ'"); spcFld.Add("40HQ", c40HQ); Dictionary<string, string> c45 = new Dictionary<string, string>(); c45.Add("C", "count(CtrKey)"); c45.Add("F", "CtrSize = '45'"); spcFld.Add("45'", c45); if (showEIR) { Dictionary<string, string> c20_EIR = new Dictionary<string, string>(); c20_EIR.Add("C", "count(CtrKey)"); c20_EIR.Add("F", "CtrSize = '20' and EirPrinted>0"); spcFld.Add("20' EIR", c20_EIR); Dictionary<string, string> c40_EIR = new Dictionary<string, string>(); c40_EIR.Add("C", "count(CtrKey)"); c40_EIR.Add("F", "CtrSize = '40' and CtrType <> '40HQ' and EirPrinted>0"); spcFld.Add("40' EIR", c40_EIR); Dictionary<string, string> c40HQ_EIR = new Dictionary<string, string>(); c40HQ_EIR.Add("C", "count(CtrKey)"); c40HQ_EIR.Add("F", "CtrType = '40HQ' and EirPrinted>0"); spcFld.Add("40HQ EIR", c40HQ_EIR); Dictionary<string, string> c45_EIR = new Dictionary<string, string>(); c45_EIR.Add("C", "count(CtrKey)"); c45_EIR.Add("F", "CtrSize = '45' and EirPrinted>0"); spcFld.Add("45' EIR", c45_EIR); Dictionary<string, string> cTTL = new Dictionary<string, string>(); cTTL.Add("C", "sum(CtrTeu)"); cTTL.Add("F", ""); spcFld.Add("TTL(Teu)", cTTL); Dictionary<string, string> cTTL_EIR = new Dictionary<string, string>(); cTTL_EIR.Add("C", "sum(CtrTeu)"); cTTL_EIR.Add("F", "EirPrinted>0"); spcFld.Add("TTL(Teu) EIR", cTTL_EIR); } uc_ReportGen.ReportRun = runRep; uc_ReportGen.ReportTitle = ft; uc_ReportGen.ReportGenFileName = "Top Account List.xls"; uc_ReportGen.RepGen.InputDataSource = dataTB; uc_ReportGen.RepGen.UdfFieldsTitle = udfFieldsTitle; uc_ReportGen.RepGen.TopFields = topFields; //uc_ReportGen.SpcFieldsReplaceTTL = true; uc_ReportGen.RepGen.LeftFields = leftFields; uc_ReportGen.RepGen.TopTTLFields = topTTLFields; uc_ReportGen.RepGen.TopSort = topSort; uc_ReportGen.RepGen.LeftSort = lefSort; uc_ReportGen.RepGen.SpcTopLastRowFields = spcFld; uc_ReportGen.RepGen.ShowFieldsTitle = true; uc_ReportGen.RepGen.ShowComputeZero = true; uc_ReportGen.RepGen.ShowRightTTL = true; uc_ReportGen.RepGen.ShowBottomTTL = true; uc_ReportGen.RepGen.ComputeExpress = "sum(CtrTeu)"; //统计的方式:除spc外,所有数据都用此统计方式 uc_ReportGen.RepGen.ShowRowNo = false; //uc_ReportGen.ShowZero = false; uc_ReportGen.RepGen.FieldTTLName = "TTL"; uc_ReportGen.RepGen.TopTTLName = "TTL(Teu)"; uc_ReportGen.RepGen.LeftTTLName = "TTL"; uc_ReportGen.RepGen.SpcSortColumn = "L:Desc"; } } }
05-31
<%@ Page Title="商品详情" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApplication1.WebForm3" %> <asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server"> <div class="product-container"> <asp:Image ID="imgProduct" runat="server" CssClass="product-image" /> <div class="product-info"> <h1><asp:Literal ID="ltProductName" runat="server" /></h1> <div class="product-price"> <asp:Literal ID="ltPrice" runat="server" /> </div> <div class="product-description"> <h3>商品描述</h3> <asp:Literal ID="ltDescription" runat="server" /> </div> <div class="product-stock"> <span>库存: </span> <asp:Literal ID="ltStock" runat="server" /> </div> <asp:Button ID="btnAddToCart" runat="server" Text="加入购物车" CssClass="btn btn-primary" OnClick="btnAddToCart_Click" /> </div> </div> </asp:Content> 前端代码 using System; using System.Data; using System.Data.SqlClient; using System.Configuration; namespace WebApplication1 { public partial class WebForm3 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { int productId; if (int.TryParse(Request.QueryString["id"], out productId)) { LoadProductDetails(productId); } else { Response.Redirect("~/Default.aspx"); } } } private void LoadProductDetails(int productId) { string connString = ConfigurationManager.ConnectionStrings["DB-NetShopsConnectionString"].ConnectionString; using (SqlConnection conn = new SqlConnection(connString)) { string query = @"SELECT p.ProductID, p.ProductName, p.Description, p.Price, p.StockQuantity, i.ImagePath FROM Products p LEFT JOIN ProductImages i ON p.ProductID = i.ProductID WHERE p.ProductID = @ProductID"; SqlCommand cmd = new SqlCommand(query, conn); cmd.Parameters.AddWithValue("@ProductID", productId); try { conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { ltProductName.Text = reader["ProductName"].ToString(); ltDescription.Text = reader["Description"].ToString(); ltPrice.Text = $"{Convert.ToDecimal(reader["Price"]):C}"; ltStock.Text = reader["StockQuantity"].ToString(); if (!string.IsNullOrEmpty(reader["ImagePath"].ToString())) { imgProduct.ImageUrl = reader["ImagePath"].ToString(); } } reader.Close(); } catch (Exception ex) { // 记录错误日志 System.Diagnostics.Debug.WriteLine(ex.Message); } } } protected void btnAddToCart_Click(object sender, EventArgs e) { int productId; if (int.TryParse(Request.QueryString["id"], out productId)) { // 添加到购物车的逻辑 // 可以使用Session或数据库存储购物车信息 } } } } 后端代码 解决报错
06-12
using System; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.Configuration; namespace WebApplication1 { public partial class WebForm3 : System.Web.UI.Page { private int currentProductId; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (!ValidateRequestParameters()) { Response.Redirect("~/Default.aspx"); return; } LoadProductDetails(currentProductId); LoadRelatedProducts(currentProductId); LogPageVisit(currentProductId); } } /// <summary> /// 验证请求参数并获取商品ID /// </summary> private bool ValidateRequestParameters() { if (!int.TryParse(Request.QueryString["id"], out currentProductId)) { ShowErrorMessage("无效的商品ID参数"); return false; } if (currentProductId <= 0) { ShowErrorMessage("商品ID必须为正整数"); return false; } return true; } /// <summary> /// 加载商品详情 /// </summary> private void LoadProductDetails(int productId) { string connString = GetConnectionString(); if (string.IsNullOrEmpty(connString)) { ShowErrorMessage("数据库连接配置错误"); return; } try { using (var conn = new SqlConnection(connString)) { // 获取商品基本信息和图片 string query = @" SELECT p.ProductID, p.ProductName, p.Subtitle, p.Description, p.Price, p.DiscountPrice, p.StockQuantity, p.CategoryID, p.Rating, p.ReviewCount, c.CategoryName, pi.ImagePath, STRING_AGG(pv.VariantName, ', ') AS AvailableVariants FROM Products p INNER JOIN Categories c ON p.CategoryID = c.CategoryID LEFT JOIN ProductImages pi ON p.ProductID = pi.ProductID AND pi.IsDefault = 1 LEFT JOIN ProductVariants pv ON p.ProductID = pv.ProductID WHERE p.ProductID = @ProductID GROUP BY p.ProductID, p.ProductName, p.Subtitle, p.Description, p.Price, p.DiscountPrice, p.StockQuantity, p.CategoryID, p.Rating, p.ReviewCount, c.CategoryName, pi.ImagePath"; using (var cmd = new SqlCommand(query, conn)) { cmd.Parameters.AddWithValue("@ProductID", productId); conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { DisplayProductDetails(reader); productContainer.Visible = true; } else { ShowErrorMessage("找不到指定的商品"); } } } } } catch (SqlException sqlEx) { LogError($"SQL错误: {sqlEx.Message}", sqlEx); ShowErrorMessage("数据库连接错误,请稍后再试"); } catch (Exception ex) { LogError($"加载商品信息失败: {ex.Message}", ex); ShowErrorMessage("加载商品信息时出错"); } } /// <summary> /// 显示商品详情到页面控件 /// </summary> private void DisplayProductDetails(SqlDataReader reader) { // 基本信息 ltProductName.Text = HttpUtility.HtmlEncode(reader["ProductName"].ToString()); ltSubtitle.Text = HttpUtility.HtmlEncode(reader["Subtitle"].ToString()); ltCategory.Text = HttpUtility.HtmlEncode(reader["CategoryName"].ToString()); // 价格 decimal price = Convert.ToDecimal(reader["Price"]); ltPrice.Text = price.ToString("C"); if (!Convert.IsDBNull(reader["DiscountPrice"]) && price > Convert.ToDecimal(reader["DiscountPrice"])) { ltDiscountPrice.Text = Convert.ToDecimal(reader["DiscountPrice"]).ToString("C"); } // 库存 int stock = Convert.ToInt32(reader["StockQuantity"]); ltStock.Text = stock.ToString(); ltStockStatus.Text = stock > 0 ? "<span class='text-success'><i class='bi bi-check-circle'></i>有货</span>" : "<span class='text-danger'><i class='bi bi-x-circle'></i>缺货</span>"; // 评分 decimal rating = Convert.ToDecimal(reader["Rating"]); ltRating.Text = GenerateRatingStars(rating); ltReviewCount.Text = reader["ReviewCount"].ToString(); // 图片 string imagePath = reader["ImagePath"]?.ToString() ?? ""; imgProduct.ImageUrl = !string.IsNullOrEmpty(imagePath) ? imagePath : "~/Images/default-product.jpg"; // 描述 ltDescription.Text = HttpUtility.HtmlEncode(reader["Description"].ToString()); // 商品型号 if (!reader.IsDBNull(reader.GetOrdinal("AvailableVariants"))) { ltAvailableVariants.Text = reader["AvailableVariants"].ToString(); } } /// <summary> /// 生成评分星星HTML /// </summary> private string GenerateRatingStars(decimal rating) { int fullStars = (int)rating; bool hasHalfStar = (rating - fullStars) >= 0.5M; int emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0); return $@" {string.Concat(Enumerable.Repeat("<i class='bi bi-star-fill text-warning'></i>", fullStars))} {(hasHalfStar ? "<i class='bi bi-star-half text-warning'></i>" : "")} {string.Concat(Enumerable.Repeat("<i class='bi bi-star text-warning'></i>", emptyStars))} <span class='ms-2'>{rating:F1}</span>"; } /// <summary> /// 加载相关商品 /// </summary> private void LoadRelatedProducts(int productId) { string connString = GetConnectionString(); if (string.IsNullOrEmpty(connString)) return; try { using (var conn = new SqlConnection(connString)) { // 获取同类别的前4个相关商品 string query = @" SELECT TOP 4 p.ProductID, p.ProductName, p.Price, pi.ImagePath FROM Products p INNER JOIN Categories c ON p.CategoryID = c.CategoryID CROSS APPLY ( SELECT TOP 1 ImagePath FROM ProductImages WHERE ProductID = p.ProductID ORDER BY IsDefault DESC ) pi WHERE p.CategoryID = ( SELECT CategoryID FROM Products WHERE ProductID = @ProductID ) AND p.ProductID <> @ProductID ORDER BY NEWID()"; using (var cmd = new SqlCommand(query, conn)) { cmd.Parameters.AddWithValue("@ProductID", productId); conn.Open(); rptRelatedProducts.DataSource = cmd.ExecuteReader(); rptRelatedProducts.DataBind(); } } } catch (Exception ex) { LogError($"加载相关商品失败: {ex.Message}", ex); } } /// <summary> /// 添加到购物车按钮点击事件 /// </summary> protected void btnAddToCart_Click(object sender, EventArgs e) { if (!ValidateRequestParameters()) return; try { // 获取用户选择的型号 string variant = Request.Form["product_variant"]; // 获取数量 int quantity; if (!int.TryParse(txtQuantity.Value, out quantity) || quantity < 1) { quantity = 1; } // 添加到购物车 Cart cart = GetOrCreateCart(); cart.AddItem(currentProductId, quantity, variant); // 更新购物车数量显示 UpdateCartBadge(cart.TotalItems); // 显示成功消息 ClientScript.RegisterStartupScript(GetType(), "AddToCartSuccess", "showToast('success', '商品已添加到购物车!');", true); } catch (Exception ex) { LogError($"添加到购物车失败: {ex.Message}", ex); ClientScript.RegisterStartupScript(GetType(), "AddToCartError", "showToast('error', '添加到购物车失败,请重试');", true); } } /// <summary> /// 记录页面访问 /// </summary> private void LogPageVisit(int productId) { try { string connString = GetConnectionString(); using (var conn = new SqlConnection(connString)) { string query = @" INSERT INTO ProductVisits (ProductID, UserIP, VisitDate) VALUES (@ProductID, @UserIP, GETDATE())"; using (var cmd = new SqlCommand(query, conn)) { cmd.Parameters.AddWithValue("@ProductID", productId); cmd.Parameters.AddWithValue("@UserIP", GetUserIP()); conn.Open(); cmd.ExecuteNonQuery(); } } } catch { // 访问日志记录失败不影响主流程 } } /// <summary> /// 获取或创建用户购物车 /// </summary> private Cart GetOrCreateCart() { Cart cart = Session["ShoppingCart"] as Cart; if (cart == null) { cart = new Cart(); Session["ShoppingCart"] = cart; } return cart; } /// <summary> /// 更新页面购物车徽章显示 /// </summary> private void UpdateCartBadge(int count) { // 查找母版页中的购物车徽章 var cartBadge = Master?.FindControl("cartBadge") as System.Web.UI.HtmlControls.HtmlGenericControl; if (cartBadge != null) { cartBadge.InnerText = count.ToString(); cartBadge.Visible = count > 0; } } /// <summary> /// 获取数据库连接字符串 /// </summary> private string GetConnectionString() { return WebConfigurationManager.ConnectionStrings["DB-NetShopsConnectionString"]?.ConnectionString; } /// <summary> /// 获取用户IP地址 /// </summary> private string GetUserIP() { string ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(ip)) { ip = Request.ServerVariables["REMOTE_ADDR"]; } else { string[] addresses = ip.Split(','); if (addresses.Length != 0) { return addresses[0]; } } return ip; } /// <summary> /// 显示错误消息 /// </summary> private void ShowErrorMessage(string message) { if (ltErrorMessage != null) { ltErrorMessage.Text = $"<div class='alert alert-danger'>{HttpUtility.HtmlEncode(message)}</div>"; ltErrorMessage.Visible = true; productContainer.Visible = false; } } /// <summary> /// 记录错误日志 /// </summary> private void LogError(string message, Exception ex) { // 实际项目中应使用日志框架(如log4net/NLog) System.Diagnostics.Debug.WriteLine($"{message}\n{ex}"); // 也可以保存到数据库或文件 try { string logMessage = $"[{DateTime.Now}] {message}\nException: {ex}\n\n"; System.IO.File.AppendAllText(Server.MapPath("~/App_Data/error.log"), logMessage); } catch { // 文件记录失败时不中断 } } } /// <summary> /// 购物车项 /// </summary> public class CartItem { public int ProductId { get; set; } public int Quantity { get; set; } public string Variant { get; set; } public DateTime AddedTime { get; set; } = DateTime.Now; } /// <summary> /// 购物车类 /// </summary> public class Cart { public List<CartItem> Items { get; } = new List<CartItem>(); public int TotalItems => Items.Sum(item => item.Quantity); public decimal TotalPrice { get { // 实际项目中应从数据库获取当前价格 return 0; // 简化为0 } } /// <summary> /// 添加商品到购物车 /// </summary> public void AddItem(int productId, int quantity, string variant = "") { var existingItem = Items.FirstOrDefault(i => i.ProductId == productId && i.Variant == variant); if (existingItem != null) { existingItem.Quantity += quantity; } else { Items.Add(new CartItem { ProductId = productId, Quantity = quantity, Variant = variant }); } } /// <summary> /// 从购物车移除商品 /// </summary> public void RemoveItem(int productId, string variant = "") { var itemToRemove = Items.FirstOrDefault(i => i.ProductId == productId && i.Variant == variant); if (itemToRemove != null) { Items.Remove(itemToRemove); } } /// <summary> /// 清空购物车 /// </summary> public void Clear() { Items.Clear(); } } } 根据后端代码更新数据库代码,使网页能够正常运行
最新发布
06-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值