(转)返璞归真 asp.net mvc (1) - 添加、查询、更新和删除的 Demo

返璞归真 asp.net mvc (1) - 添加、查询、更新和删除的 Demo



作者:webabcd


介绍
以Northwind为示例数据库,使用asp.net mvc 1.0实现添加操作、查询操作、更新操作和删除操作


示例
1、Model(使用ADO.NET Entity Framework做ORM)
CategorySystem.cs(业务逻辑

 

 1 using System;
 2 
 3 using System.Collections.Generic;
 4 
 5 using System.Linq;
 6 
 7 using System.Web;
 8 
 9 
10 
11 namespace MVC.Models
12 
13 {
14 
15     /**//// <summary>
16 
17     /// MVC 之 Model
18 
19     /// Category 业务层逻辑
20 
21     /// </summary>
22 
23     public class CategeorySystem
24 
25     {
26 
27         // Northwind 的 ObjectContext
28 
29         private NorthwindEntities ctx = new NorthwindEntities();
30 
31 
32 
33         /**//// <summary>
34 
35         /// 获取 Category 列表
36 
37         /// </summary>
38 
39         /// <returns></returns>
40 
41         public List<Categories> GetCategory()
42 
43         {
44 
45             return ctx.Categories.ToList();
46 
47         }
48 
49 
50 
51         /**//// <summary>
52 
53         /// 获取 Category 实体
54 
55         /// </summary>
56 
57         /// <param name="categoryId">类别 ID</param>
58 
59         /// <returns></returns>
60 
61         public Categories GetCategory(int categoryId)
62 
63         {
64 
65             return ctx.Categories.FirstOrDefault(p => p.CategoryID == categoryId);
66 
67         }
68 
69     }
70 
71 }

 

ProductSystem.cs(业务逻辑

  1 using System;
  2 
  3 using System.Collections.Generic;
  4 
  5 using System.Linq;
  6 
  7 using System.Web;
  8 
  9 
 10 
 11 namespace MVC.Models
 12 
 13 {
 14 
 15     /**//// <summary>
 16 
 17     /// MVC 之 Model
 18 
 19     /// Product 业务层逻辑
 20 
 21     /// </summary>
 22 
 23     public class ProductSystem
 24 
 25     {
 26 
 27         // // Northwind 的 ObjectContext
 28 
 29         private NorthwindEntities ctx = new NorthwindEntities();
 30 
 31 
 32 
 33         /**//// <summary>
 34 
 35         /// 获取产品列表
 36 
 37         /// </summary>
 38 
 39         /// <param name="pageIndex">页索引</param>
 40 
 41         /// <param name="pageSize">页大小</param>
 42 
 43         /// <returns></returns>
 44 
 45         public List<Products> GetProduct(int pageIndex, int pageSize)
 46 
 47         {
 48 
 49             return ctx.Products.OrderBy(p => p.ProductID).Skip(pageIndex * pageSize).Take(pageSize).ToList();
 50 
 51         }
 52 
 53 
 54 
 55         /**//// <summary>
 56 
 57         /// 获取产品
 58 
 59         /// </summary>
 60 
 61         /// <param name="productId">产品 ID</param>
 62 
 63         /// <returns></returns>
 64 
 65         public Products GetProduct(int productId)
 66 
 67         {
 68 
 69             return ctx.Products.FirstOrDefault(p => p.ProductID == productId);
 70 
 71         }
 72 
 73 
 74 
 75         /**//// <summary>
 76 
 77         /// 新增产品
 78 
 79         /// </summary>
 80 
 81         /// <param name="product">产品的 Entity</param>
 82 
 83         public void AddProduct(Products product)
 84 
 85         {
 86 
 87             ctx.AddToProducts(product);
 88 
 89         }
 90 
 91 
 92 
 93         /**//// <summary>
 94 
 95         /// 删除产品
 96 
 97         /// </summary>
 98 
 99         /// <param name="product">产品的 Entity</param>
100 
101         public void DeleteProduct(Products product)
102 
103         {
104 
105             product.Order_Details.Load();
106 
107             ctx.DeleteObject(product);
108 
109         }
110 
111 
112 
113         /**//// <summary>
114 
115         /// 在此对象的上下文中保存修改(增/删/改的操作)
116 
117         /// </summary>
118 
119         public void Save()
120 
121         {
122 
123             ctx.SaveChanges();
124 
125         }
126 
127 
128 
129         /**//// <summary>
130 
131         /// 在此对象的上下文中创建 EntityKey
132 
133         /// </summary>
134 
135         /// <param name="entitySetName">实体集的名称</param>
136 
137         /// <param name="entity">实体</param>
138 
139         /// <returns></returns>
140 
141         public System.Data.EntityKey CreateEntityKey(string entitySetName, object entity)
142 
143         {
144 
145             return ctx.CreateEntityKey(entitySetName, entity);
146 
147         }
148 
149     }
150 
151 }

ValidationEntity.cs(合法性验证)

 1 using System;
 2 
 3 using System.Collections.Generic;
 4 
 5 using System.Linq;
 6 
 7 using System.Web;
 8 
 9 
10 
11 namespace MVC.Models
12 
13 {
14 
15     /**//// <summary>
16 
17     /// 验证信息的实体
18 
19     /// </summary>
20 
21     public class ValidationEntity
22 
23     {
24 
25         /**//// <summary>
26 
27         /// 验证的错误信息
28 
29         /// </summary>
30 
31         public string ErrorMessage { get; set; }
32 
33         /**//// <summary>
34 
35         /// 产生错误信息的属性名称
36 
37         /// </summary>
38 
39         public string PropertyName { get; set; }
40 
41         
42 
43         public ValidationEntity(string errorMessage)
44 
45         {
46 
47             ErrorMessage = errorMessage;
48 
49         }
50 
51 
52 
53         public ValidationEntity(string errorMessage, string propertyName)
54 
55         {
56 
57             ErrorMessage = errorMessage;
58 
59             PropertyName = propertyName;
60 
61         }
62 
63     }
64 
65 }

Product.cs(合法性验证)

  1 using System;
  2 
  3 using System.Collections.Generic;
  4 
  5 using System.Linq;
  6 
  7 using System.Web;
  8 
  9 
 10 
 11 namespace MVC.Models
 12 
 13 {
 14 
 15     /**//// <summary>
 16 
 17     /// 扩展 Product 实体
 18 
 19     /// 主要是为了对 Product 实体的各个属性做输入的合法性验证
 20 
 21     /// </summary>
 22 
 23     public partial class Products
 24 
 25     {
 26 
 27         List<ValidationEntity> info = new List<ValidationEntity>();
 28 
 29 
 30 
 31         /**//// <summary>
 32 
 33         /// 对 Product 实体所做的修改是否通过了合法性验证
 34 
 35         /// </summary>
 36 
 37         public bool IsValid
 38 
 39         {
 40 
 41             get 
 42 
 43             {
 44 
 45                 return GetValidation().Count() == 0;
 46 
 47             }
 48 
 49         }
 50 
 51         
 52 
 53         /**//// <summary>
 54 
 55         /// 返回验证信息列表
 56 
 57         /// </summary>
 58 
 59         /// <returns></returns>
 60 
 61         public List<ValidationEntity> GetValidation()
 62 
 63         {
 64 
 65             return info;
 66 
 67         }
 68 
 69 
 70 
 71         /**//// <summary>
 72 
 73         /// 重写部分方法 OnProductNameChanging
 74 
 75         /// 用于在 ProductName 属性改变前,对其做合法性验证
 76 
 77         /// </summary>
 78 
 79         /// <param name="value"></param>
 80 
 81         partial void OnProductNameChanging(string value)
 82 
 83         {
 84 
 85             if (string.IsNullOrEmpty(value))
 86 
 87                 info.Add(new ValidationEntity("请输入产品名称", "ProductName"));
 88 
 89         }
 90 
 91 
 92 
 93         /**//// <summary>
 94 
 95         /// 重写部分方法 OnUnitPriceChanging
 96 
 97         /// 用于在 UnitPrice 属性改变前,对其做合法性验证
 98 
 99         /// </summary>
100 
101         /// <param name="value"></param>
102 
103         partial void OnUnitPriceChanging(global::System.Nullable<decimal> value)
104 
105         {
106 
107             if (value == null)
108 
109                 info.Add(new ValidationEntity("请输入单价", "UnitPrice"));
110 
111             else if (((decimal)value) > 100)
112 
113                 info.Add(new ValidationEntity("输入的单价过高", "UnitPrice"));
114 
115         }
116 
117     }
118 
119 }

2、Controller
ProductController.cs

  1 using System;
  2 
  3 using System.Collections.Generic;
  4 
  5 using System.Linq;
  6 
  7 using System.Web;
  8 
  9 using System.Web.Mvc;
 10 
 11 using System.Web.Mvc.Ajax;
 12 
 13 
 14 
 15 using MVC.Models;
 16 
 17 
 18 
 19 namespace MVC.Controllers
 20 
 21 {
 22 
 23     /**//// <summary>
 24 
 25     /// MVC 之 Controller
 26 
 27     /// 这里体现了 Convention over Configuration
 28 
 29     /// Controller 类必须以字符串 Controller 做类名称的结尾,字符串 Controller 之前的字符串为 Controller 的名称,类中的方法名为 Action 的名称
 30 
 31     /// 例如 ProductController, Controller 的名称为:Product;其中的 Action 名称有 Index, Details, Edit 等
 32 
 33     /// </summary>
 34 
 35     public class ProductController : Controller // 需要继承自 System.Web.Mvc.Controller 或者实现 IController 接口
 36 
 37     {
 38 
 39         ProductSystem ps = new ProductSystem();
 40 
 41 
 42 
 43         // Action 的返回值必须为 ActionResult 或 void 
 44 
 45 
 46 
 47         /**//// <summary>
 48 
 49         /// 获取 Product 的列表
 50 
 51         /// </summary>
 52 
 53         /// <param name="pageIndex">页索引</param>
 54 
 55         /// <returns></returns>
 56 
 57         public ActionResult Index(int pageIndex)
 58 
 59         {
 60 
 61             int pageSize = 10;
 62 
 63             var products = ps.GetProduct(pageIndex, pageSize);
 64 
 65 
 66 
 67             // 此 Action 对应的 View 为(按查找的先后顺序) Views/Product/Index.aspx, Views/Product/Index.ascx, Views/Shared/Index.aspx, Views/Shared/Index.ascx
 68 
 69             // 其所对应的 View 的关联对象为 products
 70 
 71             return View("Index", products);
 72 
 73         }
 74 
 75 
 76 
 77         public ActionResult Details(int id)
 78 
 79         {
 80 
 81             var product = ps.GetProduct(id);
 82 
 83 
 84 
 85             if (product == null)
 86 
 87                 return View("NotFound");
 88 
 89             else
 90 
 91                 // 对应的 View 的名称默认为 Action 的名称,所以此处所对应的 View 的名称为 Details
 92 
 93                 return View(product);
 94 
 95         }
 96 
 97 
 98 
 99         public ActionResult Edit(int id)
100 
101         {
102 
103             var product = ps.GetProduct(id);
104 
105 
106 
107             if (product == null)
108 
109             {
110 
111                 return View("NotFound");
112 
113             }
114 
115             else
116 
117             {
118 
119                 product.CategoriesReference.Load();
120 
121 
122 
123                 // 编辑 Product 的时候需要在一个 DropDownList 中选择其所对应的 Category, 所以这里要构造一个名为 CategoryAll 的 ViewData
124 
125                 // 因为 Categories 已经是 Product 的属性了,所以这里的 ViewData 的 key 不能为 Categories
126 
127                 if (product.Categories == null)
128 
129                     ViewData["CategoryAll"] = new SelectList(new CategeorySystem().GetCategory(), "CategoryId", "CategoryName");
130 
131                 else
132 
133                     ViewData["CategoryAll"] = new SelectList(new CategeorySystem().GetCategory(), "CategoryId", "CategoryName", product.Categories.CategoryID);
134 
135 
136 
137                 return View("Edit", product);
138 
139             }
140 
141         }
142 
143 
144 
145         // 可以用 AcceptVerbs 来声明 Action 所对应的 http 方法
146 
147         [AcceptVerbs(HttpVerbs.Post)]
148 
149         public ActionResult Edit(int id, FormCollection formValues)
150 
151         {
152 
153             var product = ps.GetProduct(id);
154 
155 
156 
157             // 可以通过这种方式一一为 Product 对象的属性赋值
158 
159             // product.ProductName = Request.Form["ProductName"];
160 
161 
162 
163             // 也可以通过 UpdateModel, 让系统自动为属性赋值(通过反射的方式,取得对象的属性名称,然后和 Request 的 key 做匹配,匹配成功的则赋值)
164 
165             UpdateModel<Products>(product);
166 
167 
168 
169             var category = new CategeorySystem().GetCategory(int.Parse(Request.Form["MyCategory"]));
170 
171             product.CategoriesReference.EntityKey = ps.CreateEntityKey("Categories", category);
172 
173 
174 
175             // 通过以下的方式让 UpdateModel 只更新指定属性
176 
177             // string[] allowedProperties = new[] { "ProductName", "UnitPrice" };
178 
179             // UpdateModel(product, allowedProperties);
180 
181 
182 
183             if (!product.IsValid)
184 
185             {
186 
187                 foreach (var validation in product.GetValidation())
188 
189                 {
190 
191                     // 设置验证信息
192 
193                     ModelState.AddModelError(validation.PropertyName, validation.ErrorMessage);
194 
195                 }
196 
197 
198 
199                 if (product.Categories == null)
200 
201                     ViewData["CategoryAll"] = new SelectList(new CategeorySystem().GetCategory(), "CategoryId", "CategoryName");
202 
203                 else
204 
205                     ViewData["CategoryAll"] = new SelectList(new CategeorySystem().GetCategory(), "CategoryId", "CategoryName", product.Categories.CategoryID);
206 
207 
208 
209                 return View(product);
210 
211             }
212 
213 
214 
215             ps.Save();
216 
217 
218 
219             // 跳转到指定的 Action
220 
221             return RedirectToAction("Details", new { id = product.ProductID });
222 
223         }
224 
225 
226 
227         public ActionResult Create()
228 
229         {
230 
231             Products product = new Products()
232 
233             {
234 
235                 ProductName = "请输入产品名称"
236 
237             };
238 
239 
240 
241             return View(product);
242 
243         }
244 
245 
246 
247         // 可以为参数添加声明,如下例:[Bind(Include = "ProductName")],客户端提交的数据中,只有 ProductName 会被绑定到 Product 对象上
248 
249         // [Bind(Include = "ProductName")] 这样的 attribute 也可以声明在类上,用于指定类中需要被绑定的属性
250 
251         [AcceptVerbs(HttpVerbs.Post)]
252 
253         public ActionResult Create([Bind(Include = "ProductName")] Products product)
254 
255         {
256 
257             if (!product.IsValid)
258 
259             {
260 
261                 foreach (var issue in product.GetValidation())
262 
263                 {
264 
265                     ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
266 
267                 }
268 
269 
270 
271                 return View(product);
272 
273             }
274 
275 
276 
277             ps.AddProduct(product);
278 
279             ps.Save();
280 
281 
282 
283             return RedirectToAction("Details", new { id = product.ProductID });
284 
285         }
286 
287 
288 
289         public ActionResult Delete(int id)
290 
291         {
292 
293             var product = ps.GetProduct(id);
294 
295 
296 
297             if (product == null)
298 
299                 return View("NotFound");
300 
301             else
302 
303                 return View(product);
304 
305         }
306 
307 
308 
309         [AcceptVerbs(HttpVerbs.Post)]
310 
311         public ActionResult Delete(int id, string confirmButton)
312 
313         {
314 
315             var product = ps.GetProduct(id);
316 
317 
318 
319             if (product == null)
320 
321                 return View("NotFound");
322 
323 
324 
325             ps.DeleteProduct(product);
326 
327             ps.Save();
328 
329 
330 
331             return View("Deleted");
332 
333         }
334 
335     }
336 
337 }

 

3、View(以列表页为例)
Index.aspx

 

  1 <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MVC.Models.Products>>" %>
  2 
  3 
  4 
  5 <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
  6 
  7     Index
  8 
  9 </asp:Content>
 10 
 11 <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
 12 
 13     <h2>
 14 
 15         Index</h2>
 16 
 17     <table>
 18 
 19         <tr>
 20 
 21             <th>
 22 
 23             </th>
 24 
 25             <th>
 26 
 27                 ProductID
 28 
 29             </th>
 30 
 31             <th>
 32 
 33                 ProductName
 34 
 35             </th>
 36 
 37             <th>
 38 
 39                 UnitPrice
 40 
 41             </th>
 42 
 43         </tr>
 44 
 45         <%  // 因为本页集成了 System.Web.Mvc.ViewPage<IEnumerable<MVC.Models.Products>>
 46 
 47             // 所以这里的 Model 就是 System.Web.Mvc.ViewPage<IEnumerable<MVC.Models.Products>> 的 Model 属性
 48 
 49             foreach (var item in Model)
 50 
 51             { %>
 52 
 53         <tr>
 54 
 55             <td>
 56 
 57                 <!--这里的 Html 属性类型为 System.Web.Mvc.HtmlHelper-->
 58 
 59                 <%= Html.ActionLink("Delete", "Delete", new { id = item.ProductID })%>
 60 
 61                 |
 62 
 63                 <%= Html.ActionLink("Edit", "Edit", new { id = item.ProductID }) %>
 64 
 65             </td>
 66 
 67             <td>
 68 
 69                 <%= Html.ActionLink(item.ProductID.ToString(), "Details", new { id=item.ProductID })%>
 70 
 71             </td>
 72 
 73             <td>
 74 
 75                 <%= Html.Encode(item.ProductName) %>
 76 
 77             </td>
 78 
 79             <td>
 80 
 81                 <%= Html.Encode(String.Format("{0:F}", item.UnitPrice)) %>
 82 
 83             </td>
 84 
 85         </tr>
 86 
 87         <% } %>
 88 
 89     </table>
 90 
 91     <p>
 92 
 93         <%= Html.RouteLink("上一页", "Products", new { pageIndex = Convert.ToInt32(Html.ViewContext.RouteData.Values["pageIndex"]) - 1 })%>
 94 
 95         |
 96 
 97         <%= Html.RouteLink("下一页", "Products", new { pageIndex = Convert.ToInt32(Html.ViewContext.RouteData.Values["pageIndex"]) + 1 })%>
 98 
 99     </p>
100 
101 </asp:Content>

 

 

OK
[源码下载]

posted @ 2012-05-29 18:39  loverszhaokai  阅读(202)  评论(0编辑  收藏  举报