Nancy簡單實戰之NancyMusicStore(四):實現購物車

原文:Nancy簡單實戰之NancyMusicStore(四):實現購物車

前言

上一篇,我們完成了商品的詳情和商品的管理,這一篇我們來完成最后的一個購物車功能。

購物車,不外乎這幾個功能:添加商品到購物車,刪除購物車中的商品,對購物車中的商品進行結算。

MVC MusicStore中,在Models文件夾中添加了一個ShoppingCart類來處理這一塊的內容

這個類就類似我們的業務邏輯層,所以這里也采用了和它一樣的做法。

取購物車

首先來看一下取購物車這個靜態方法:

public static ShoppingCart GetCart(NancyContext context)
{var cart = new ShoppingCart();cart.ShoppingCartId = cart.GetCartId(context);return cart;
}

取購物車,其實只是給購物車類里面的ShoppingCartId賦值,而ShoppingCartId值是來自GetCartId方法:

public string GetCartId(NancyContext context)
{if (context.Request.Session[CartSessionKey] == null){if (context.CurrentUser != null){context.Request.Session[CartSessionKey] = context.CurrentUser.UserName;}else{Guid tempCartId = Guid.NewGuid();context.Request.Session[CartSessionKey] = tempCartId.ToString();}}return context.Request.Session[CartSessionKey].ToString();
}

在MVC MusicStrore中,這個方法的參數用的是HttpContextBase,而在Nancy中,Nancy有自己的Context

所以自然就是直接用Nancy自帶的Context。這里是每次都會為新用戶創建一個guid存儲在session中

并用這個session作為購物車的唯一標識。

在Nancy中,用到了session的話,需要在啟動器中啟用Session,不然Session會一直是空的。

我們在CustomerBootstrapper類的ApplicationStartup方法中添加啟動Cookie的代碼,具體如下:

protected override void ApplicationStartup(TinyIoCContainer container,IPipelines pipelines)
{//enable the cookieCookieBasedSessions.Enable(pipelines);//Prevent errors on LinuxStaticConfiguration.DisableErrorTraces = false;
}

購物車商品數量

還記得我們在布局_Layout.cshtml里面還有一個購物車中的商品數量還沒有實現。我們現在把這個功能補上。

在ShoppingCart中添加下面取數的方法,這個方法是根據購物車的id去數據取出相應的數據。

public int GetCount()
{string cmd = "public.get_total_count_by_cartid";var res = DBHelper.ExecuteScalar(cmd, new{cid = ShoppingCartId}, null, null, CommandType.StoredProcedure);return Convert.ToInt32(res);
}

然后我們新建一個ShopCartModule.cs,并在構造函數中添加取數的方法。

Get["/cartsummary"] = _ =>
{var cart = ShoppingCart.GetCart(this.Context);return Response.AsJson(cart.GetCount());
};

最后在_Layout.cshtml中用ajax調用這個方法即可:

 $.ajax({url: "/shoppingcart/cartsummary",method: "get",dataType: "json",success: function (res) {$("#cart-status").text('Cart (' + res + ')');}
});

這樣我們就徹底把布局頁完成了。下面是具體的效果

12932

下面就專注購物車的其他實現了。

添加商品到購物車

添加商品到購物車,有這兩種情況:

  • 添加了一個購物車中沒有的商品(要向購物車中插一條記錄)

  • 添加了一個購物車中已經有了的商品(要向購物車中更新一條記錄)

所以我們就可以得到下面的實現(ShoppingCart):

public void AddToCart(Album album)
{string getItemCmd = "public.get_cart_item_by_cartid_and_albumid";var cartItem = DBHelper.QueryFirstOrDefault<Cart>(getItemCmd, new{cid = ShoppingCartId,aid = album.AlbumId}, null, null, CommandType.StoredProcedure);string addToCartCmd = string.Empty;if (cartItem == null){// Create a new cart item if no cart item existsAddCartItem(cartItem, album.AlbumId);}else{UpdateCartItem(cartItem);}
}

在添加之前都要向根據購物車標識和專輯(商品)標識去判斷。此時我們在Module中的實現就比較簡單了

Get["/addtocart/{id:int}"] = _ =>
{int id = 0;if (int.TryParse(_.id, out id)){string cmd = "public.get_album_by_aid";var addedAlbum = DBHelper.QueryFirstOrDefault<Album>(cmd, new{aid = id}, null, null, CommandType.StoredProcedure);var cart = ShoppingCart.GetCart(this.Context);cart.AddToCart(addedAlbum);}return Response.AsRedirect("~/");
};

后臺邏輯處理好了,我們把商品加入購物車的入口在那呢?入口就在商品詳情頁下面的【Add to cart】按鈕

12955

當我們把加入購物車后,可以看到右上角的數量在改變,同時跳轉回了首頁。

12959

購物車首頁

我們已經完成了添加商品到購物車,但是我們還看不到我們購物車里面有些什么商品,所以要有一個購物車首頁。

購物車的首頁,本質就是一個列表,這個列表所列了購物車內的所有商品,包含了這些商品的基本信息和購物車的訂單總金額。

Get["/index"] = _ =>
{var cart = ShoppingCart.GetCart(this.Context);// Set up our ViewModelvar viewModel = new ShoppingCartViewModel{CartItems = cart.GetCartItems(),CartTotal = cart.GetTotal()};// Return the viewreturn View["Index", viewModel];
};

視圖如下 :

@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<NancyMusicStore.ViewModels.ShoppingCartViewModel>
@{ViewBag.Title = "Shopping Cart";
}
<h3><em>Review</em> your cart:
</h3>
<p class="button"><a href="javascript:;">Checkout >></a>
</p>
<div id="update-message">
</div>
<table><tr><th>Album Name</th><th>Price (each)</th><th>Quantity</th><th></th></tr>@foreach (var item in Model.CartItems){<tr id="row-@item.RecordId"><td><a href="/store/details/@item.AlbumId">@item.Title</a></td><td>@item.Price</td><td id="item-count-@item.RecordId">@item.Count</td><td><a href="javascript:void(0);" class="RemoveLink" data-id="@item.RecordId">Remove from cart</a></td></tr>}<tr><td>Total</td><td></td><td></td><td id="cart-total">@Model.CartTotal</td></tr>
</table>

具體效果如下所示:

shoppingcart

從購物車中刪除商品

刪除購物車中的商品也是同樣的有兩種情況

  • 一種是讓購物車中的商品數量減1

  • 一種是從購物車中直接刪掉商品,不同的是刪除的同時返回了商品的數量,這個數量用于在頁面展示。

public int RemoveFromCart(int id)
{string getItemCmd = "public.get_cart_item_by_cartid_and_recordid";var cartItem = DBHelper.QueryFirstOrDefault<Cart>(getItemCmd, new{cid = ShoppingCartId,rid = id}, null, null, CommandType.StoredProcedure);int itemCount = 0;if (cartItem != null){                if (cartItem.Count > 1){UpdateCartItemCount(cartItem, itemCount);                   }else{RemoveCartItem(cartItem.RecordId);}}return itemCount;
}

同時還要在購物車列表頁面添加相應的JS處理

@section scripts{<script type="text/javascript">$(function () {$(".RemoveLink").click(function () {var recordToDelete = $(this).attr("data-id");if (recordToDelete != '') {$.post("/shoppingcart/removefromcart", { "id": recordToDelete },function (data) {if (data.ItemCount == 0) {$('#row-' + data.deleteid).fadeOut('slow');} else {$('#item-count-' + data.deleteId).text(data.itemCount);}$('#cart-total').text(data.cartTotal);$('#update-message').text(data.message);$('#cart-status').text('Cart (' + data.cartCount + ')');});}});});</script>
}

最后的話就是結算,下面進入我們的結算操作

購物車結算

購物車結算,也就是提交訂單,也就是填寫一些用戶的相關信息,比如:姓名、地址、聯系電話等等這些信息,見下圖。

checkout

我們在Modules文件夾中添加一個CheckOutModule.cs用來處理結算相關的功能。

要結算,必須要登錄,所以我們要首先添加需要授權的這句代碼this.RequiresAuthentication();

然后再考慮其他事情。

提交訂單的后臺操作如下:

Post["/addressandpayment"] = _ =>
{var order = this.Bind<Order>();order.Username = this.Context.CurrentUser.UserName;order.OrderDate = DateTime.UtcNow;string cmd = "public.add_order";var res = DBHelper.ExecuteScalar(cmd, new{odate = order.OrderDate,uname = order.Username,fname = order.FirstName,lname = order.LastName,adr = order.Address,cn = order.City,sn = order.State,pcode = order.PostalCode,cname = order.Country,ph = order.Phone,ea = order.Email,t = order.Total}, null, null, CommandType.StoredProcedure);if (Convert.ToInt32(res) != 0){order.OrderId = Convert.ToInt32(res);var cart = ShoppingCart.GetCart(this.Context);cart.CreateOrder(order);string redirectUrl = string.Format("/checkout/complete/{0}", res.ToString());return Response.AsRedirect(redirectUrl);}return View["AddressAndPayment"];
};

先是創建了一張訂單,這張訂單只包含了一些用戶信息。訂單創建好了之后才去創建訂單明細,最后就是返回訂單完成頁:

complete

創建訂單明細的方法也是寫在Models下面的ShoppingCart中,具體如下:

public int CreateOrder(Order order)
{decimal orderTotal = 0;var cartItems = GetCartItems();                        foreach (var item in cartItems){                AddOrderDetails(new OrderDetail{AlbumId = item.AlbumId,OrderId = order.OrderId,UnitPrice = item.Price,Quantity = item.Count});// Set the order total of the shopping cartorderTotal += (item.Count * item.Price);}UpdateOrderTotal(order.OrderId, orderTotal);         // Empty the shopping cartEmptyCart();// Return the OrderId as the confirmation numberreturn order.OrderId;
}

這里做的操作主要有三個:

  1. 把購物車中的商品插入到訂單明細表中
  2. 更新訂單主表的總金額
  3. 清空當前的購物車

到這里,我們的NancyMusicStore已經是到了收尾階段。就差部署上線了啊!!

所以在下一篇,將是介紹Nancy的部署,分別在Windows和Linux下部署。

本文也已經同步到 Nancy之大雜燴

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390407.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390407.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390407.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

劍指 Offer 32 - I. 從上到下打印二叉樹

從上到下打印出二叉樹的每個節點&#xff0c;同一層的節點按照從左到右的順序打印。 例如: 給定二叉樹: [3,9,20,null,null,15,7], 3/ \9 20/ \15 7返回&#xff1a; [3,9,20,15,7] 提示&#xff1a; 節點總數 < 1000 解題思路 使用隊列實現層序遍歷 代碼 /*** …

數據庫表命名 單數復數_數據是還是數據是? “數據”一詞是單數還是復數?

數據庫表命名 單數復數Ill cut right to the chase: the word "data" is plural. Its the plural form of Latin word "datum." Many data. One datum.我將緊追其后&#xff1a;“數據”一詞是復數形式。 它是拉丁文“基準”的復數形式。 許多數據。 一個基…

《七步掌握業務分析》讀書筆記六

分析技術和呈現格式 詞匯表 強有力溝通的一個重要內容是一致地使用術語和慣用語。每次談話都涉及對術語的共同理解。 工作流圖&#xff08;也稱為流程圖、UNL活動圖和過程圖&#xff09; 工作流程把一個或多個業務過程的細節可視化地呈現出來&#xff0c;以澄清理解或提出過程改…

Mysql數據庫--語句整理/提升/進階/高級使用技巧

一、基礎 1、說明&#xff1a;創建數據庫CREATE DATABASE database-name 2、說明&#xff1a;刪除數據庫drop database dbname3、說明&#xff1a;備份sql server--- 創建 備份數據的 deviceUSE masterEXEC sp_addumpdevice disk, testBack, c:\mssql7backup\MyNwind_1.dat--- …

1104. 二叉樹尋路

在一棵無限的二叉樹上&#xff0c;每個節點都有兩個子節點&#xff0c;樹中的節點 逐行 依次按 “之” 字形進行標記。 如下圖所示&#xff0c;在奇數行&#xff08;即&#xff0c;第一行、第三行、第五行……&#xff09;中&#xff0c;按從左到右的順序進行標記&#xff1b;…

javascript 代碼_如何開始對JavaScript代碼進行單元測試

javascript 代碼We all know we should write unit tests. But, its hard to know where to start and how much time to devote to tests compared to actual implementation. So, where to start? And is it just about testing code or do unit tests have other benefits?…

個人作業——軟件工程實踐總結作業

一、請回望暑假時的第一次作業&#xff0c;你對于軟件工程課程的想象 1&#xff09;對比開篇博客你對課程目標和期待&#xff0c;“希望通過實踐鍛煉&#xff0c;增強計算機專業的能力和就業競爭力”&#xff0c;對比目前的所學所練所得&#xff0c;在哪些方面達到了你的期待和…

(轉)在阿里,我們如何管理代碼分支?

阿里妹導讀&#xff1a;代碼分支模式的選擇并沒有絕對的正確和錯誤之分&#xff0c;關鍵是與項目的規模和發布節奏相匹配。阿里協同研發平臺在經過眾多實踐歷練后&#xff0c;總結出了一套獨創的分支管理方法&#xff1a;AoneFlow&#xff0c;通過兼備靈活高效與簡單實用的流程…

WIN10系統 截圖或者某些程序時屏幕會自動放大怎么辦

右擊這個應用程序&#xff0c;兼容性&#xff0c;以兼容模式運行&#xff0c;同時勾選高DPI設置時禁止顯示縮放即可

css背景圖片添加url_CSS背景圖片–如何向您的Div添加圖片URL

css背景圖片添加urlSay you want to put an image or two on a webpage. One way is to use the background-image CSS property. 假設您要在網頁上放置一兩個圖片。 一種方法是使用background-image CSS屬性。 This property applies one or more background images to an el…

golang基礎01

1.環境變量&#xff1a;go env//代碼目錄和第三方庫文件set GOPATHC:\Users\hanxiaodong\go//go安裝目錄set GOROOTC:\Gopath里要配置&#xff1a;goroot/bin;和gopath/bin; gopath目錄下三個文件夾&#xff1a;pkg&#xff1a;編譯好的庫文件 .a 文件bin&#xff1a;可執行文件…

hugo 能做web開發嗎_如何自托管Hugo Web應用

hugo 能做web開發嗎After hosting with Netlify for a few years, I decided to head back to self hosting. There are a few reasons for that, but the main reasoning was that I had more control over how things worked. 在Netlify托管了幾年之后&#xff0c;我決定回到…

資源 | 深度學習課程入門與介紹

【1】Andrew NG Deep Learning.ai http://deeplearning.ai/網易云課堂&#xff08;中文字幕&#xff09;&#xff1a;http://mooc.study.163.com/smartSpec/detail/1001319001.htm推薦理由&#xff1a;Andrew Ng老師是講課的能手&#xff0c;很多人認識他是從Stanford的經典《機…

PostCSS 以及 cssnext語法

本文是對近兩天學習postcss的總結&#xff0c;在這里分享給大家。 如有錯誤&#xff0c;還請指正&#xff01; 什么是postcss postcss 一種對css編譯的工具&#xff0c;類似babel對js的處理&#xff0c;常見的功能如&#xff1a; 1 . 使用下一代css語法 2 . 自動補全瀏覽器前綴…

5187. 收集足夠蘋果的最小花園周長

給你一個用無限二維網格表示的花園&#xff0c;每一個 整數坐標處都有一棵蘋果樹。整數坐標 (i, j) 處的蘋果樹有 |i| |j| 個蘋果。 你將會買下正中心坐標是 (0, 0) 的一塊 正方形土地 &#xff0c;且每條邊都與兩條坐標軸之一平行。 給你一個整數 neededApples &#xff0c…

虛擬機 VMware Workstation12 安裝OS X 系統

Windows下虛擬機安裝Mac OS X —– VMware Workstation12安裝Mac OS X 10.11本文即將介紹WIN虛擬MAC的教程。完整詳細教程&#xff08;包含安裝中的一些問題&#xff09;【并且適用其他mac os x版本】Windows下 VM12虛擬機安裝OS X 10.11(詳細教程) 工具/原料 Mac OS X 10.11 鏡…

aws dynamodb_DynamoDB備忘單–您需要了解的有關2020 AWS認證開發人員助理認證的Amazon Dynamo DB的所有信息

aws dynamodbThe emergence of cloud services has changed the way we build web-applications. This in turn has changed the responsibilities of a Web Developer. 云服務的出現改變了我們構建Web應用程序的方式。 反過來&#xff0c;這改變了Web開發人員的職責。 We use…

北大CIO走進龍泉寺交流研討會圓滿舉行

緣起 2016年4月16日&#xff0c;北京大學信息化與信息管理研究中心秘書長姚樂博士與國家非物質文化遺產蔚縣剪紙傳承人周淑英女士一起在龍泉寺拜見了中國佛教協會會長、龍泉寺主持學誠法師。在拜見學誠法師時&#xff0c;姚樂博士與學誠法師聊到了“賢二機器僧”和人工智能。姚…

負載均衡種類

http://blog.csdn.net/zhoudaxia/article/details/23672319DNS DNS輪詢是最簡單的負載均衡方式。以域名作為訪問入口&#xff0c;通過配置多條DNS A記錄使得請求可以分配到不同的服務器。DNS輪詢沒有快速的健康檢查機制&#xff0c;而且只支持WRR的調度策略導致負載很難“均衡”…

代碼流星雨是什么形式_為什么要在2020年與流星合作

代碼流星雨是什么形式Meteor, an allegedly dead development platform, is still alive and can bring massive value to your everyday coding experience.Meteor&#xff0c;據稱已失效的開發平臺&#xff0c;仍然有效&#xff0c;可以為您的日常編碼體驗帶來巨大的價值。 …