返璞归真 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(业务逻辑
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVC.Models
{
    
/// <summary>
    
/// MVC 之 Model
    
/// Category 业务层逻辑
    
/// </summary>

    public class CategeorySystem
    
{
        
// Northwind 的 ObjectContext
        private NorthwindEntities ctx = new NorthwindEntities();

        
/// <summary>
        
/// 获取 Category 列表
        
/// </summary>
        
/// <returns></returns>

        public List<Categories> GetCategory()
        
{
            
return ctx.Categories.ToList();
        }


        
/// <summary>
        
/// 获取 Category 实体
        
/// </summary>
        
/// <param name="categoryId">类别 ID</param>
        
/// <returns></returns>

        public Categories GetCategory(int categoryId)
        
{
            
return ctx.Categories.FirstOrDefault(p => p.CategoryID == categoryId);
        }

    }

}


ProductSystem.cs(业务逻辑

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

namespace MVC.Models
{
    
/// <summary>
    
/// MVC 之 Model
    
/// Product 业务层逻辑
    
/// </summary>

    public class ProductSystem
    
{
        
// // Northwind 的 ObjectContext
        private NorthwindEntities ctx = new NorthwindEntities();

        
/// <summary>
        
/// 获取产品列表
        
/// </summary>
        
/// <param name="pageIndex">页索引</param>
        
/// <param name="pageSize">页大小</param>
        
/// <returns></returns>

        public List<Products> GetProduct(int pageIndex, int pageSize)
        
{
            
return ctx.Products.OrderBy(p => p.ProductID).Skip(pageIndex * pageSize).Take(pageSize).ToList();
        }


        
/// <summary>
        
/// 获取产品
        
/// </summary>
        
/// <param name="productId">产品 ID</param>
        
/// <returns></returns>

        public Products GetProduct(int productId)
        
{
            
return ctx.Products.FirstOrDefault(p => p.ProductID == productId);
        }


        
/// <summary>
        
/// 新增产品
        
/// </summary>
        
/// <param name="product">产品的 Entity</param>

        public void AddProduct(Products product)
        
{
            ctx.AddToProducts(product);
        }


        
/// <summary>
        
/// 删除产品
        
/// </summary>
        
/// <param name="product">产品的 Entity</param>

        public void DeleteProduct(Products product)
        
{
            product.Order_Details.Load();
            ctx.DeleteObject(product);
        }


        
/// <summary>
        
/// 在此对象的上下文中保存修改(增/删/改的操作)
        
/// </summary>

        public void Save()
        
{
            ctx.SaveChanges();
        }


        
/// <summary>
        
/// 在此对象的上下文中创建 EntityKey
        
/// </summary>
        
/// <param name="entitySetName">实体集的名称</param>
        
/// <param name="entity">实体</param>
        
/// <returns></returns>

        public System.Data.EntityKey CreateEntityKey(string entitySetName, object entity)
        
{
            
return ctx.CreateEntityKey(entitySetName, entity);
        }

    }

}


ValidationEntity.cs(合法性验证)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVC.Models
{
    
/// <summary>
    
/// 验证信息的实体
    
/// </summary>

    public class ValidationEntity
    
{
        
/// <summary>
        
/// 验证的错误信息
        
/// </summary>

        public string ErrorMessage getset; }
        
/// <summary>
        
/// 产生错误信息的属性名称
        
/// </summary>

        public string PropertyName getset; }
        
        
public ValidationEntity(string errorMessage)
        
{
            ErrorMessage 
= errorMessage;
        }


        
public ValidationEntity(string errorMessage, string propertyName)
        
{
            ErrorMessage 
= errorMessage;
            PropertyName 
= propertyName;
        }

    }

}


Product.cs(合法性验证)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVC.Models
{
    
/// <summary>
    
/// 扩展 Product 实体
    
/// 主要是为了对 Product 实体的各个属性做输入的合法性验证
    
/// </summary>

    public partial class Products
    
{
        List
<ValidationEntity> info = new List<ValidationEntity>();

        
/// <summary>
        
/// 对 Product 实体所做的修改是否通过了合法性验证
        
/// </summary>

        public bool IsValid
        
{
            
get 
            
{
                
return GetValidation().Count() == 0;
            }

        }

        
        
/// <summary>
        
/// 返回验证信息列表
        
/// </summary>
        
/// <returns></returns>

        public List<ValidationEntity> GetValidation()
        
{
            
return info;
        }


        
/// <summary>
        
/// 重写部分方法 OnProductNameChanging
        
/// 用于在 ProductName 属性改变前,对其做合法性验证
        
/// </summary>
        
/// <param name="value"></param>

        partial void OnProductNameChanging(string value)
        
{
            
if (string.IsNullOrEmpty(value))
                info.Add(
new ValidationEntity("请输入产品名称""ProductName"));
        }


        
/// <summary>
        
/// 重写部分方法 OnUnitPriceChanging
        
/// 用于在 UnitPrice 属性改变前,对其做合法性验证
        
/// </summary>
        
/// <param name="value"></param>

        partial void OnUnitPriceChanging(global::System.Nullable<decimal> value)
        
{
            
if (value == null)
                info.Add(
new ValidationEntity("请输入单价""UnitPrice"));
            
else if (((decimal)value) > 100)
                info.Add(
new ValidationEntity("输入的单价过高""UnitPrice"));
        }

    }

}



2、Controller
ProductController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

using MVC.Models;

namespace MVC.Controllers
{
    
/// <summary>
    
/// MVC 之 Controller
    
/// 这里体现了 Convention over Configuration
    
/// Controller 类必须以字符串 Controller 做类名称的结尾,字符串 Controller 之前的字符串为 Controller 的名称,类中的方法名为 Action 的名称
    
/// 例如 ProductController, Controller 的名称为:Product;其中的 Action 名称有 Index, Details, Edit 等
    
/// </summary>

    public class ProductController : Controller // 需要继承自 System.Web.Mvc.Controller 或者实现 IController 接口
    {
        ProductSystem ps 
= new ProductSystem();

        
// Action 的返回值必须为 ActionResult 或 void 

        
/// <summary>
        
/// 获取 Product 的列表
        
/// </summary>
        
/// <param name="pageIndex">页索引</param>
        
/// <returns></returns>

        public ActionResult Index(int pageIndex)
        
{
            
int pageSize = 10;
            var products 
= ps.GetProduct(pageIndex, pageSize);

            
// 此 Action 对应的 View 为(按查找的先后顺序) Views/Product/Index.aspx, Views/Product/Index.ascx, Views/Shared/Index.aspx, Views/Shared/Index.ascx
            
// 其所对应的 View 的关联对象为 products
            return View("Index", products);
        }


        
public ActionResult Details(int id)
        
{
            var product 
= ps.GetProduct(id);

            
if (product == null)
                
return View("NotFound");
            
else
                
// 对应的 View 的名称默认为 Action 的名称,所以此处所对应的 View 的名称为 Details
                return View(product);
        }


        
public ActionResult Edit(int id)
        
{
            var product 
= ps.GetProduct(id);

            
if (product == null)
            
{
                
return View("NotFound");
            }

            
else
            
{
                product.CategoriesReference.Load();

                
// 编辑 Product 的时候需要在一个 DropDownList 中选择其所对应的 Category, 所以这里要构造一个名为 CategoryAll 的 ViewData
                
// 因为 Categories 已经是 Product 的属性了,所以这里的 ViewData 的 key 不能为 Categories
                if (product.Categories == null)
                    ViewData[
"CategoryAll"= new SelectList(new CategeorySystem().GetCategory(), "CategoryId""CategoryName");
                
else
                    ViewData[
"CategoryAll"= new SelectList(new CategeorySystem().GetCategory(), "CategoryId""CategoryName", product.Categories.CategoryID);

                
return View("Edit", product);
            }

        }


        
// 可以用 AcceptVerbs 来声明 Action 所对应的 http 方法
        [AcceptVerbs(HttpVerbs.Post)]
        
public ActionResult Edit(int id, FormCollection formValues)
        
{
            var product 
= ps.GetProduct(id);

            
// 可以通过这种方式一一为 Product 对象的属性赋值
            
// product.ProductName = Request.Form["ProductName"];

            
// 也可以通过 UpdateModel, 让系统自动为属性赋值(通过反射的方式,取得对象的属性名称,然后和 Request 的 key 做匹配,匹配成功的则赋值)
            UpdateModel<Products>(product);

            var category 
= new CategeorySystem().GetCategory(int.Parse(Request.Form["MyCategory"]));
            product.CategoriesReference.EntityKey 
= ps.CreateEntityKey("Categories", category);

            
// 通过以下的方式让 UpdateModel 只更新指定属性
            
// string[] allowedProperties = new[] { "ProductName", "UnitPrice" };
            
// UpdateModel(product, allowedProperties);

            
if (!product.IsValid)
            
{
                
foreach (var validation in product.GetValidation())
                
{
                    
// 设置验证信息
                    ModelState.AddModelError(validation.PropertyName, validation.ErrorMessage);
                }


                
if (product.Categories == null)
                    ViewData[
"CategoryAll"= new SelectList(new CategeorySystem().GetCategory(), "CategoryId""CategoryName");
                
else
                    ViewData[
"CategoryAll"= new SelectList(new CategeorySystem().GetCategory(), "CategoryId""CategoryName", product.Categories.CategoryID);

                
return View(product);
            }


            ps.Save();

            
// 跳转到指定的 Action
            return RedirectToAction("Details"new { id = product.ProductID });
        }


        
public ActionResult Create()
        
{
            Products product 
= new Products()
            
{
                ProductName 
= "请输入产品名称"
            }
;

            
return View(product);
        }


        
// 可以为参数添加声明,如下例:[Bind(Include = "ProductName")],客户端提交的数据中,只有 ProductName 会被绑定到 Product 对象上
        
// [Bind(Include = "ProductName")] 这样的 attribute 也可以声明在类上,用于指定类中需要被绑定的属性
        [AcceptVerbs(HttpVerbs.Post)]
        
public ActionResult Create([Bind(Include = "ProductName")] Products product)
        
{
            
if (!product.IsValid)
            
{
                
foreach (var issue in product.GetValidation())
                
{
                    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                }


                
return View(product);
            }


            ps.AddProduct(product);
            ps.Save();

            
return RedirectToAction("Details"new { id = product.ProductID });
        }


        
public ActionResult Delete(int id)
        
{
            var product 
= ps.GetProduct(id);

            
if (product == null)
                
return View("NotFound");
            
else
                
return View(product);
        }


        [AcceptVerbs(HttpVerbs.Post)]
        
public ActionResult Delete(int id, string confirmButton)
        
{
            var product 
= ps.GetProduct(id);

            
if (product == null)
                
return View("NotFound");

            ps.DeleteProduct(product);
            ps.Save();

            
return View("Deleted");
        }

    }

}


3、View(以列表页为例)
Index.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<MVC.Models.Products>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    
<h2>
        Index
</h2>
    
<table>
        
<tr>
            
<th>
            
</th>
            
<th>
                ProductID
            
</th>
            
<th>
                ProductName
            
</th>
            
<th>
                UnitPrice
            
</th>
        
</tr>
        
<%  // 因为本页集成了 System.Web.Mvc.ViewPage<IEnumerable<MVC.Models.Products>>
            
// 所以这里的 Model 就是 System.Web.Mvc.ViewPage<IEnumerable<MVC.Models.Products>> 的 Model 属性
            foreach (var item in Model)
            { 
%>
        
<tr>
            
<td>
                
<!--这里的 Html 属性类型为 System.Web.Mvc.HtmlHelper-->
                
<%= Html.ActionLink("Delete""Delete"new { id = item.ProductID })%>
                |
                
<%= Html.ActionLink("Edit""Edit"new { id = item.ProductID }) %>
            
</td>
            
<td>
                
<%= Html.ActionLink(item.ProductID.ToString(), "Details"new { id=item.ProductID })%>
            
</td>
            
<td>
                
<%= Html.Encode(item.ProductName) %>
            
</td>
            
<td>
                
<%= Html.Encode(String.Format("{0:F}", item.UnitPrice)) %>
            
</td>
        
</tr>
        
<% } %>
    
</table>
    
<p>
        
<%= Html.RouteLink("上一页""Products"new { pageIndex = Convert.ToInt32(Html.ViewContext.RouteData.Values["pageIndex"]) - 1 })%>
        |
        
<%= Html.RouteLink("下一页""Products"new { pageIndex = Convert.ToInt32(Html.ViewContext.RouteData.Values["pageIndex"]) + 1 })%>
    
</p>
</asp:Content>


OK
[源码下载]
posted @ 2009-04-14 10:39  webabcd  阅读(10925)  评论(30编辑  收藏  举报