⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cardetail-noscript.aspx

📁 ASP.NET Web Forms Techniques
💻 ASPX
📖 第 1 页 / 共 3 页
字号:
<%@ Page Language="C#" EnableViewState="True" EnableSessionState="True" SmartNavigation="False" %>
<%@Import Namespace="System.Data"%>
<%@Import Namespace="System.Data.SqlClient"%>

<%@ Import Namespace="Microsoft.Web.UI.WebControls" %>
<%@ Register TagPrefix="ie" Namespace="Microsoft.Web.UI.WebControls"
    Assembly="Microsoft.Web.UI.WebControls, Version=1.0.2.226, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>

<script runat="server">
// -------------------------------------------------------------------

// page-level variable to style sheet size
String sStyleSize = "Standard";

// page-level variable to hold current car ID
String sCarID;

// page-level variable to hold DataSet of values from database
DataSet oCarsDS;

// page-level array to hold current car price and finance terms
// (0) = Basic Price including extras and color option
// (1) = Annual interest rate applicable to purchase
// (2) = Interest amount included in Total Price
// (3) = Total Price including interest for finance plan (if selected)
// (4) = Number of months for finance plan (if selected)
// (5) = Monthly payment amount for finance plan (if selected)
String[] aCurrentPrice = new String[6];

// page-level variable to hold Session key for prices array
String sPricesSessionKey;

// -------------------------------------------------------------------

void Page_Load() {

  // get style sheet size from Session
  sStyleSize = (String)Session["WccStyleSize"];

  // if no value, session has expired or user entered
  // site at page other than "Home" page
  if (sStyleSize == "") {

    // write client-side code that reloads Home page and closes
    // window to browser, plus message for non-script clients
    String sReload = "<html><body><center>"
      + "<b>Your session has expired.</b><p />"
      + "<b>Please close this window and reload the Home page</b>"
      + "</center></body></html>";

    // then prevent rest of page from being processed
    Response.Write(sReload);
    Response.Flush();
    Response.End();
    return;
  }

  // get car ID from query string
  sCarID = Request.QueryString["id"];
  if (sCarID != "" && sCarID != null) {

    // get DataSet from function elsewhere in this page
    // we'll also need it almost every time a postback occurs
    oCarsDS = GetCarDetailsDS(sCarID);
    if (oCarsDS == null) {
      lblMessage.Text = "Sorry, the database cannot be accessed.";
      btnSave.Visible = false;
      return;
    }

    // specify XML source files and the matching XSLT
    // stylesheets for the two asp:Xml controls
    // have to do this on every page load as the result
    // is not persisted in the viewstate
    try {
      xmlDetailLeft.DocumentSource = "xmldata/tvdata-left-" + sCarID + ".xml";
      xmlDetailLeft.TransformSource = "xmldata/cardetail.xslt";
      xmlDetailRight.DocumentSource = "xmldata/tvdata-right-" + sCarID + ".xml";
      xmlDetailRight.TransformSource = "xmldata/cardetail.xslt";
    }
    catch (Exception e) {
      lblMessage.Text = "Error loading XML data for car details.";
    }

    if (Page.IsPostBack) {

      // get key for Prices array from the page ViewState
      sPricesSessionKey = (String)ViewState["PriceArrayKey"];

      // get array of current prices and finance terms from Session
      aCurrentPrice = (String[])Session[sPricesSessionKey];
    }
    else {

      // create random key for storing price/finance terms array in
      // user's session for this instance of the page, just in case
      // they are configuring multiple instances of the same vehicle
      Random oRand = new Random();
      sPricesSessionKey = "WCCPricesKey" + sCarID + "-"
                        + oRand.Next(0, 999).ToString();

      // store this key in the ViewState of the page
      ViewState["PriceArrayKey"] = sPricesSessionKey;

      // display details of this vehicle
      ShowCarDetails(sCarID);

      // calculate and display price for default configuration
      CalculateCarPrice();
    }
  }
}

// -------------------------------------------------------------------

// routine to show selected car details
void ShowCarDetails(String sCarID) {

  // get references to the tables in the DataSet
  DataTable oDTCar = oCarsDS.Tables["CarDetails"];
  DataTable oDTColor = oCarsDS.Tables["CarColors"];
  DataTable oDTExtras = oCarsDS.Tables["CarExtras"];
  DataTable oDTFinance = oCarsDS.Tables["FinancePMTRates"];

  // fill in Precis and image of car
  DataRow oDR = oDTCar.Rows[0];
  lblPrecis.Text = oDR["Precis"].ToString();
  String sCarName = oDR["Model"].ToString();
  imgCar.ImageUrl = "images/" + sCarName + "300.gif";
  imgCar.AlternateText = "The Xrox " + sCarName;
  elmTitle.InnerText = "Xrox " + sCarName + " - Configure and Buy";

  // fill the DataList of colors depending on setting of
  // the Standard/Metallic radio buttons
  DataView oDTView = oDTColor.DefaultView;
  oDTView.RowFilter = "IsMetallic = " + optColorType.SelectedIndex;
  dlsColors.DataSource = oDTView;
  dlsColors.DataBind();
  oDTView.RowFilter = "";

  // fill RadioButtonList with available engines
  optEngine.DataSource = oDTCar;
  optEngine.DataValueField = "EngineID";
  optEngine.DataTextField = "EngineName";
  optEngine.DataBind();

  // fill the DataGrid with the details of each engine
  dgrEngine.DataSource = oDTCar;
  dgrEngine.DataBind();

  // and select the first engine in these two lists
  optEngine.SelectedIndex = 0;
  dgrEngine.SelectedIndex = 0;

  // fill the CheckBoxList with list of available extras
  chkExtras.DataSource = oDTExtras;
  chkExtras.DataTextField = "DisplayText";
  chkExtras.DataValueField = "ExtraID";
  chkExtras.DataBind();

  lstFinanceMonths.DataSource = oDTFinance;
  lstFinanceMonths.DataTextField = "Months";
  lstFinanceMonths.DataValueField = "Payment";
  lstFinanceMonths.DataBind();

  // select the "36 months" entry as the default
  lstFinanceMonths.SelectedIndex = 5;
}

// -------------------------------------------------------------------

// routine to update price displayed in window when any options are changed
void CalculateCarPrice() {

  Decimal fPrice = 0;

  // hide Save button
  btnSave.Visible = false;

  // clear any existing finance terms from array and page
  // routine used is an event handler so have to provide the
  // parameters for Sender and EventArgs - we use null as
  // these values are not actually used in event handler code
  ClearFinanceTerms(null, null);

  try {

    // create suitable filter to get appropriate row from tblCarEngines
    String sFilter = "CarID = " + sCarID + " AND EngineID = "
                   + optEngine.SelectedItem.Value;

    // get reference to table in DataSet and select matching row
    DataTable oDTCar = oCarsDS.Tables["CarDetails"];
    DataRow[] aRows =  oDTCar.Select(sFilter, "");

    // extract price for this car/engine combination
    fPrice = (Decimal)aRows[0]["CarEnginePrice"];

    // create suitable filter to get appropriate row from tblColors
    // using color name set in background of car image cell
    sFilter = "Color = '" + tclColor.BgColor + "'";

    // get reference to table in DataSet and select matching row
    DataTable oDTColors = oCarsDS.Tables["CarColors"];
    aRows = oDTColors.Select(sFilter, "");

    // if it is a metallic color, add on the premium for this
    // stored in web.config here, but could come from a database table
    if ((Boolean)aRows[0]["IsMetallic"] == true) {
      try {
        fPrice += Decimal.Parse(ConfigurationSettings.AppSettings["XroxCarsMetallicPaint"]);
      }
      catch (Exception e) {
        lblMessage.Text = "Error in metallic paint premium in web.config.";
        lblPrice.Text = "* Error *";
        return;
      }
    }

    // get reference to tblOptionExtra in DataSet
    DataTable oDTExtras = oCarsDS.Tables["CarExtras"];

    // iterate through the list of Extras to see which are selected
    foreach (ListItem oItem in chkExtras.Items) {
      if (oItem.Selected) {

        // although we specified the ExtraID column as the DataValueField property
        // of the CheckBoxList control, it does not render any value attributes.
        // Instead so we have to look up the selected items in the original DataSet
        // using the DisplayText value from the caption of each button and then
        // extract the Price column value - alternatively we could parse it out of
        // the Text property (the caption) of the selected item

        // create suitable filter to get appropriate row from tblOptionExtra
        sFilter = "DisplayText = '" + oItem.Text + "'";
        aRows = oDTExtras.Select(sFilter, "");
        fPrice += (Decimal)aRows[0]["ExtraPrice"];
      }
    }
  }
  catch (Exception e) {
    lblMessage.Text = "Sorry, the database cannot be accessed.";
    lblPrice.Text = "* Error *";
    return;
  }

  // store total price including extras in array
  aCurrentPrice[0] = fPrice.ToString("#,##0.00");

  // update Session with new array values
  Session[sPricesSessionKey] = aCurrentPrice;

  // display price in page
  lblPrice.Text = fPrice.ToString("#,##0.00");

  // show Save button
  btnSave.Visible = true;
}

// -------------------------------------------------------------------

// routine to display finance terms for "Calculate" button
void ShowFinanceTerms(object oSender, EventArgs oArgs) {

  // clear any existing finance terms from array and page
  ClearFinanceTerms(null, null);

  // call function to calculate finance terms values
  // returns error message, or empty string string if all OK
  String sError = CalculateFinanceTerms();
  if (sError == "") {

    // display the results in the page
    lblTerms.Text = aCurrentPrice[4] + " months  at $"
      + aCurrentPrice[5] + " per month";
    lblFinanceResult.Text = "<b>Your payments will be $"
      + aCurrentPrice[5].ToString() + " per month for "
      + aCurrentPrice[4].ToString() + " months</b>.";
    lblFinanceInfo.Text = "Basic price $" + aCurrentPrice[0]
      + " plus Interest $" + aCurrentPrice[2] + " - Total price $"
      + aCurrentPrice[3] + " - APR " + aCurrentPrice[1] + "%";

    // enable the button to cancel these terms
    btnCancel.Enabled = true;

    // show Save button
    btnSave.Visible = true;
  }
  else {

    // display the error details in the page
    lblTerms.Text = "&nbsp;";
    lblFinanceResult.Text = "<b>" + sError + "</b>";
    lblFinanceInfo.Text = "";

    // hide Save button
    btnSave.Visible = false;
  }
}

// -------------------------------------------------------------------

// function to calculate payment terms from current user selections
String CalculateFinanceTerms() {

  Decimal fInterestRate;
  Decimal fBasePrice, fTotalInterest, fMonthlyPayment;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -