官方示例Music+Store(音乐商店)简易中文教程

2018-10-28 15:40

ASP.NET MVC3官方示例Music Store(音乐商店)

--简易中文教程

http://www.inxproj.com/tech/142#comments

前言:

本文来源于微软MVC3官方教程.在http://mvcmusicstore.codeplex.com/可以下载到最新版本的源码和英文PDF教程.

和英文教程一样,本文将分成十章节来介绍这个音乐商店的建立.

导航目录:

? ? ? ? ? ? ? ? ? ?

(一)前期准备,新建MVC项目 (二)控制器 (三)视图与模型 (四)数据访问

(五)使用脚手架功能创建编辑页面

(六)使用Data Annotation为模型进行验证 (七)成员和权限

(八)Ajax刷新效果的购物车 (九)注册和支付 (十)最终版本修正与发布

综述:

原文:The MVC Music Store is a tutorial application that introduces and explains step-by-step how to use ASP.NET MVC and Visual Web Developer for web development. We’ll be starting slowly, so beginner level web development experience is okay.

The application we’ll be building is a simple music store. There are three main parts to the application: shopping, checkout, and administration.

翻译:MVC音乐商店是一个示例应用程序,它将一步一步介绍和说明如何使用ASP.NET MVC和Visual Web Developer进行Web开发。本教程会慢慢讲解,因此,即使你是一名初学者也没问题。

我们要开发的是一个简单的音乐商店,主要包括三个主要功能:购物,支付,管理。

原文:Visitors can browse Albums by Genre: 翻译:访客可以根据专辑类别浏览唱片

原文:They can view a single album and add it to their cart: 翻译:可以查看单个唱片并且加入到购物车:

原文:They can review their cart, removing any items they no longer want:

翻译:可以查看购物车,并且移除不需要的商品:

原文:Proceeding to Checkout will prompt them to login or register for a user account. 翻译:支付订单的时候会提示用户注册或者登陆帐号。

原文:After creating an account, they can complete the order by filling out shipping and payment information. To keep things simple, we’re running an amazing promotion: everything’s free if they enter promotion code “FREE”!

翻译:创建一个帐号之后,示例程序采用“免费代码”支付的方似乎模拟支付过程。(其实这不算翻译啦)

原文:After ordering, they see a simple confirmation screen: 翻译:订单完成之后会有一个简单的确认界面:

In addition to customer-faceing pages, we’ll also build an administrator section that shows a list of albums from which Administrators can Create, Edit, and Delete albums:

除了访客浏览的界面之外,我们还创建了一个后台管理界面,用于管理唱片的增删查改:

前期准备:

需要的开发工具:

? ? ? ?

Visual Web Developer 2010 Express SP1 或者 Visual Studio 2010 SP1 SQL Server Compact 或者 SQL Server

Asp.Net MVC3 和 ASP.NET MVC 3 Tools Update 一份MvcMusicStore-Assets的代码

笔者用的是 Visual Studio 2010 SP1+Sql Server 2008开发的,上文提到的Visual Web Developer 2010 Express和SQL Server Compact都是免费的,大家可以到微软的官方下载。MVC3这个就是必须的,MVC3中文的安装方式有点麻烦,之后会独立一个文章说明一下怎样安装,急的朋友也可以Google一下怎样安装。笔者之前一直纳闷为什么自己的控制器添加界面和官方教程里面的界面有所不同,后来和朋友沟通才发现,原来少装了一个ASP.NET MVC 3 Tools Update,这个工具可以让程序员减少编码,是个好东西。MvcMusicStore-Assets这个在http://mvcmusicstore.codeplex.com下载的压缩包里面有。

软件的下载地址:

Visual Studio Web Developer Express SP1 prerequisites

http://www.microsoft.com/web/gallery/install.aspx?appid=VWD2010SP1Pack ASP.NET MVC 3 Tools Update

http://www.microsoft.com/web/gallery/install.aspx?appid=MVC3 SQL Server Compact 4.0 – including both runtime and tools support

http://www.microsoft.com/web/gallery/install.aspx?appid=SQLCE;SQLCEVSTools_4_0

ASP.NET MVC3 Music Store 简易中文教程.(一)前期准备,新建MVC项目

发表于143 天前 ? 技术研究 ? 评论数 7

新建MVC项目:

我们从在VS2010的文件菜单中选择“新建->项目”开始,进入“新建项目”对话框。

选择“Visual C#->Web”,选择“ASP.NET MVC 3 空 Web 应用程序”,将项目命名为“MvcMusicStore”,按“确定”按纽

点击确定按钮之后,将会出现以下对话框。选择空模板,Razor试图引擎,勾选使用HTML5标记

点击OK按钮之后,VS就会创建一个新的MVC项目。由下图可以看出,其实这个空模板,并不是真正的完全没有内容。VS2010为我们创建了一个MVC项目的基本框架。

对于一些基本的文件夹,ASP.NET MVC规范其命名

文件夹 用途 /Controllers 控制器处理来自浏览器的输入,并返回相应页面给用户。 /Views /Models /Content /Scripts 存放视图模板。 存放数据模型,用于操控数据。 存放图片、CSS及其它静态内容。 存放JavaScript文件。

ASP.NET MVC3 Music Store 简易中文教程.(二)控制器

发表于143 天前 ? 技术研究 ? 评论数 10

原文:With traditional web frameworks, incoming URLs are typically mapped to files on disk. For example: a request for a URL like “/Products.aspx” or “/Products.php” might be processed by a “Products.aspx” or “Products.php” file.

Web-based MVC frameworks map URLs to server code in a slightly different way. Instead of mapping incoming URLs to files, they instead map URLs to methods on classes. These classes are called “Controllers” and they are responsible for processing incoming HTTP requests, handling user input, retrieving and saving data, and determining the response to send back to the client (display HTML, download a file, redirect to a different URL, etc.).

翻译:传统的Web框架,URL通常直接映射到磁盘上的文件。例如:类似”/Products.aspx” 或 “/Products.php”这样的URL请求,可能直接由“Products.aspx“或”Products.php“文件进行处理。

MVC Web框架使用不同的方式映射URL到服务器代码,MVC将URL映射到类的方法,而这些类被称为“控制器“,由控制器响应和处理HTTP请求、用户输入、接收和保存数据,并且决定如何将响应发回到客户端(显示HTML,下载文件,重定向URL等)。

添加HomeController

原文:We’ll begin our MVC Music Store application by adding a Controller class that will handle URLs to the Home page of our site. We’ll follow the default naming conventions of ASP.NET MVC and call it HomeController.

翻译:我们通过添加一个控制器类来开始我们的MVC Music Store应用程序,它将用于处理链接到网站首页的请求。遵照ASP.NET MVC的命名约定,我们给这个类取名“HomeController”。

右键Controller文件夹,点击添加,然后选择Controller。如下图:

接着就会出现一个对话框(如果你没有安装MVCToolsUpdate,对话框将不会是这样)。如下图:

添加之后,Controller文件夹会增加一个HomeController.cs的文件,其内容如下

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17.

using System;

using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc;

namespace MyMusic.Controllers {

public class HomeController : Controller { //

// GET: /Home/

public ActionResult Index() {

return View(); } } }

修改Index方法为

1. 2. 3. 4.

public string Index() {

return “Hello from Home”; }

启动程序,浏览器访问主页会显示以下效果:

添加StoreController

重复之前添加HomeController的操作,添加一个StoreController控制器。

类似HomeController一样,修改Index方法,并添加另外两个方法,完整代码如下。

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19.

using System;

using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc;

namespace MyMusic.Controllers {

public class StoreController : Controller { //

// GET: /Store/ public string Index() {

return “Hello from Store.Index()”; } //

// GET: /Store/Browse public string Browse()

20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31.

{

return “Hello from Store.Browse()”; } //

// GET: /Store/Details public string Details() {

return “Hello from Store.Details()”; } } }

再次启动项目,并访问一下地址: /Store /Store/Browse /Store/Details

效果如图:

修改Browse,Detail方法:

1. 2. 3. 4. 5. 6. 7. 8. 9.

//

// GET: /Store/Browse?genre=Disco public string Browse(string genre) {

string message = HttpUtility.HtmlEncode(“Store.Browse, Genre = ” + genre); return message; } //

// GET: /Store/Details/5

10. 11. 12. 13. 14.

public string Details(int id) {

string message = “Store.Details, ID = ” + id; return message; }

Browse方法接收一个querystring参数genre,并动态显示到页面。 访问:/Store/Browse?Genre=Disco

注意: 这里使用HttpUtility.HtmlEncode方法审核用户输入,这可以防止用户使用类似/Store/Browse?Genre=

这样的链接做出邪恶的行为。

Detail方法和Browse方法有所不同,Detail方法可以不通过QueryString传递参数。ASP.NET MVC的默认路由设置把URL中动作方法后面的部份看成一个名叫“ID”的参数,如果你的动作方法有一个叫“ID”的参数,ASP.NET MVC会自动这部份做为参数传递。

访问:/Store/Details/5

访问:/Store/Details?id=5

访问:/Store/Details (悲剧了!- -!因为Detail方法没有0个参数的重载嘛。)

到目前为止我们一共做了下面的事:

? ? ? ?

在VS中创建了一个新的ASP.NET MVC项目 了解了ASP.NET MVC应用程序的基本的目录结构

创建了两个控制器类:HomeController和StoreController 在控制器中添加了动作方法响应URL请求并把文本返回给浏览器

ASP.NET MVC3 Music Store 简易中文教程.(三)视图与模型

发表于142 天前 ? 技术研究 ? 评论数 2

原文:So far we’ve just been returning strings from controller actions. That’s a nice way to get an idea of how controllers work, but it’s not how you’d want to build a real web application. We are going to want a better way to generate HTML back to browsers visiting our site – one where we can use template files to more easily customize the HTML content send back. That’s exactly what Views do.

这不是翻译:之前我们只是通过控制器返回字符串,我们真正需要的是返回一系列的页面内容。此时,我们就需要视图模板了。

添加试图模板:

首先我们需要将之前HomeController更改的内容恢复回来,代码如下:

1. 2. 3. 4. 5. 6. 7. 8. 9.

public class HomeController : Controller { //

// GET: /Home/

public ActionResult Index() {

return View(); } }

把鼠标移动到Index方法上面,然后点击右键,点击菜单里面的Add View选项:

“添加视图”对话框让我们方便快捷地生成视图模板文件。视图模板的名称默认以控制器上的方法名命名,我们在HomeController的Index方法上使用右键菜单上的“添加视图”,因此“添加视图”对话框默认填写Index作为视图名称,一般情况下不需要改变任何选项,点击“添加”按纽。

添加之后,在项目里的/Views/Home文件夹,会自动创建一个名为Index.cshtml的视图模板。

Index.cshtml的文件名和所在的文件夹的命名非常重要,它遵循MVC3的约定。文件夹名\\Views\\Home匹配HomeController控制器,Index匹配控制器的Index方法。

通过刚才添加视图的对话框生成的Index.cshtml文件代码如下:

1. 2. 3. 4.

@{

ViewBag.Title = “Index”; }

Index

这是一个Razor视图,对Razor比较陌生的同学可以Google了解一下,以后本站也会有相关的介绍。 @{}是Razor语言的标记,ViewBag.Title是页面标题的属性。 【h2】标签里面的是文本内容。 我们稍微做一下修改,然后访问一下:

1. 2. 3. 4.

@{

ViewBag.Title = “Index”; }

我是主页!

使用Layout模板设置页面公共属性:

大多数的网站都有相同元素,旧版本的Asp.Net我们可以通过母板页的使用来节省编码量,在MVC引用了一个类似母板页的功能,就是Layout模板,其位置在/Views/Shared文件夹。

其内容如下:

1. 2. 3. 4. 5. 6. 7.

@ViewBag.Title

8.

9. 10. 11. 12. 13. 14.

@RenderBody()

其中除了@RenderBody()以外的内容都是公共内容,@RenderBody()相当于母板页的占位符。 我们修改一下Layout模板,让其显示我们想要的样式。

1. 2. 3. 4. 5. 6.

@ViewBag.Title

7.

8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.

ASP.NET MVC MUSIC STORE

@RenderBody()

更新样式表和文件:

在官方网站下载的源文件里面,把MvcMusicStore-Assets/Content文件夹里面的内容都复制到项目的Content文件夹里头。

红圈内的为有更改的文件:

再运行一次程序,效果如下:

使用模型传递数据到视图页面:

静态网页让人提不起精神,我们必须弄点动态的网页出来看看。

MVC全称是Model-View-Controller,Controller和View都介绍过了,接下来的当然是Model了。

简单的来说,MVC模式就是用户提出一个请求,Controller接收请求并寻找视图绑定的Model,然后传递这个Model给视图,最终视图接收Model,并根据模板生成HTML代码。

现在,我们创建两个模型类,一个是音乐类型类Genre.cs,一个是唱片类

Album.cs

然后再Genre类添加一个属性:

1. 2. 3. 4. 5. 6. 7.

namespace MyMusic.Models {

public class Genre {

public string Name { get; set; } } }

同样方法添加Album类并修改代码:

1. 2. 3. 4. 5. 6. 7. 8.

namespace MyMusic.Models {

public class Album {

public string Title { get; set; } public Genre Genre { get; set; } } }

原文:Note: In case you’re wondering, the { get; set; } notation is making use of C#’s auto-implemented properties feature. This gives us the benefits of a property without requiring us to declare a backing field.

就是说,这是C#的新特性,可以直接用 { get; set; } 来定义,不用在蛋疼的多声明一个_name了。 我们再修改StoreController.cs的Details方法,使其返回一个View:

1. 2. 3. 4. 5.

public ActionResult Details(int id) {

var album = new Album { Title = “Album ” + id }; return View(album); }

噢,这里忘记了。还需要引用命名空间:

1. using MyMusic.Models;

官方教程的是using MvcMusicStore.Models;,但因为我之前有一个这名字的项目了,所以就换了个名字。

接着我们就要利用MVC的模板生成一个Details视图,在生成视图之前,我们要生成一下项目:

然后和之前一样在Details方法点击右键添加视图:

并且在添加视图对话框,勾选建立强类型视图,并选择Album作为要传递的Model类型:

视图建立后,就会生成Store文件夹和Details.cshtml文件:

打开Details.cshtml文件,修改【h2】标签的内容。同时我们可以发现用Razor视图可以像C#那样用“.”点出提示出来。amazing!

1.

Album: @Model.Title

运行程序并访问URL /Store/Details/5,我们看到了唱片的信息:

继续修改StoreController的Browse方法:

1. 2. 3. 4. 5.

public ActionResult Browse(string genre) {

var genreModel = new Genre { Name = genre }; return View(genreModel); }

44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. 83. 84. 85. 86. 87.

else {

// 如果已经存在一个购物车,则增加对应唱片的数量 cartItem.Count++; }

// 保存更改

storeDB.SaveChanges(); }

public int RemoveFromCart(int id) {

// 获得购物车

var cartItem = storeDB.Carts.Single( cart => cart.CartId == ShoppingCartId && cart.RecordId == id); int itemCount = 0; if (cartItem != null) {

if (cartItem.Count > 1) {

cartItem.Count–;

itemCount = cartItem.Count; } else {

storeDB.Carts.Remove(cartItem); }

// 保存更改

storeDB.SaveChanges(); }

return itemCount; }

public void EmptyCart() {

var cartItems = storeDB.Carts.Where(cart => cart.CartId == ShoppingCartId); foreach (var cartItem in cartItems) {

storeDB.Carts.Remove(cartItem); }

// 保存更改

storeDB.SaveChanges(); }

public List GetCartItems() {

return storeDB.Carts.Where(cart => cart.CartId == ShoppingCartId).ToList();

88. 89. 90. 91. 92. 93. 94. 95. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. 111. 112. 113. 114. 115. 116. 117. 118. 119. 120. 121. 122. 123. 124. 125. 126. 127. 128. 129. 130. 131.

}

public int GetCount() {

// 获取每个唱片的数量并叠加

int? count = (from cartItems in storeDB.Carts where cartItems.CartId == ShoppingCartId select (int?)cartItems.Count).Sum(); // 返回0如果所有实体都是空的。 return count ?? 0; }

public decimal GetTotal() {

// 统计唱片总价

decimal? total = (from cartItems in storeDB.Carts where cartItems.CartId == ShoppingCartId

select (int?)cartItems.Count * cartItems.Album.Price).Sum(); return total ?? decimal.Zero; }

public int CreateOrder(Order order) {

decimal orderTotal = 0;

var cartItems = GetCartItems(); //遍历购物车的唱片,添加到订单详细 foreach (var item in cartItems) {

var orderDetail = new OrderDetail {

AlbumId = item.AlbumId, OrderId = order.OrderId, UnitPrice = item.Album.Price, Quantity = item.Count };

// 设置购物车的订单总价

orderTotal += (item.Count * item.Album.Price); storeDB.OrderDetails.Add(orderDetail); }

// 设置订单总价

order.Total = orderTotal; // 保存订单

storeDB.SaveChanges(); // 清空购物车 EmptyCart(); // 返回订单ID

return order.OrderId;

132. 133. 134. 135. 136. 137. 138. 139. 140. 141. 142. 143. 144. 145. 146. 147. 148. 149. 150. 151. 152. 153. 154. 155. 156. 157. 158. 159. 160. 161. 162. 163. 164.

}

// 使用HttpContextBase访问cookies.(这里是Session啦) public string GetCartId(HttpContextBase context) {

if (context.Session[CartSessionKey] == null) {

if (!string.IsNullOrWhiteSpace(context.User.Identity.Name)) {

context.Session[CartSessionKey] = context.User.Identity.Name; } else {

// 创建一个GUID

Guid tempCartId = Guid.NewGuid();

// 用Cookies的形式向客户端返回tempCartId(Session啦) context.Session[CartSessionKey] = tempCartId.ToString(); } }

return context.Session[CartSessionKey].ToString(); }

// 当用户已登录,便使购物车关联其用户名

public void MigrateCart(string userName) {

var shoppingCart = storeDB.Carts.Where(c => c.CartId == ShoppingCartId); foreach (Cart item in shoppingCart) {

item.CartId = userName; }

storeDB.SaveChanges(); } } }

我们的ShoppingCart需要传递一些复合信息给它的视图,但这些信息并没有清晰地映射到模型类。我们不想为了迎合视图需要而修改模型,模型类应属于其专用领域,而不是为用户界面服务。一种解决方法是使用ViewBag传递相关信息,就像之前在StoreManager中为下拉框传递数据一样。但是过多使用ViewBag会变得难以管理。

另一种方案是使用视图模型(ViewModels),使用这种模式可以优化使用“强类型”创建的视图,并且在视图模板中动态显示需要的值/内容。控制器可以填充和传递这些“优化过的视图类”供视图模板使用,并在视图模板支持类型安全、编译检查和编辑器的智能感应功能。

我们创建两个视图模型供ShoppingCartController使用:ShoppingCartViewModel保存用户购物车的内容,ShoppingCartRemoveViewModel在用户从购物车移除物品时显示确认信息。

首先我们需要在项目根部新建一个“ViewModels”文件夹

并在这个文件夹添加两个类:ShoppingCartViewModel和ShoppingCartRemoveViewModel

1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

using System;

using System.Collections.Generic; using System.Linq; using System.Web; using MyMusic.Models;

namespace MyMusic.ViewModels {

public class ShoppingCartViewModel {

11. 12. 13. 14.

public List CartItems { get; set; } public decimal CartTotal { get; set; } } }

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16.

using System;

using System.Collections.Generic; using System.Linq; using System.Web;

namespace MyMusic.ViewModels {

public class ShoppingCartRemoveViewModel {

public string Message { get; set; } public decimal CartTotal { get; set; } public int CartCount { get; set; } public int ItemCount { get; set; } public int DeleteId { get; set; } } }

添加ShoppingCart控制器:

Shopping Cart控制器有三个主要功能:往购物车添加物品,从购物车中移除物品以及显示购物车的物品。它将使用我们刚刚创建的三个类:ShoppingCartViewModel, ShoppingCartRemoveViewModel和 ShoppingCart。和StoreController和StoreManagerController一样,我们为它添加一个MusicStoreEntities类的实例。

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18.

using System;

using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MyMusic.Models; using MyMusic.ViewModels;

namespace MyMusic.Controllers {

public class ShoppingCartController : Controller {

MusicStoreEntities storeDB = new MusicStoreEntities(); //

// GET: /ShoppingCart/ public ActionResult Index() {

var cart = ShoppingCart.GetCart(this.HttpContext);


官方示例Music+Store(音乐商店)简易中文教程.doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:2015年(电大)中国现代文学专题(15秋)专题三 满分答案

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: