原文:返璞归真 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 { get; set; }
        /**//// <summary>
        /// 产生错误信息的属性名称
        /// </summary>
        public string PropertyName { get; set; }
        
        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

[源码下载]

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

  1. ASP.NET网页动态添加、更新或删除数据行

    ASP.NET网页动态添加.更新或删除数据行 看过此篇<ASP.NET网页动态添加数据行> http://www.cnblogs.com/insus/p/3247935.html的网友,也 ...

  2. ASP.NET MVC对WebAPI接口操作(添加,更新和删除)

    昨天<怎样操作WebAPI接口(显示数据)>http://www.cnblogs.com/insus/p/5670401.html 既有使用jQuery,也有使作HttpClient来从数 ...

  3. ASP.NET MVC 5 - 添加一个模型

    在本节中,您将添加一些类,这些类用于管理数据库中的电影.这些类是ASP.NET MVC 应用程序中的"模型(Model)". 您将使用.NET Framework 数据访问技术En ...

  4. 返璞归真 asp.net mvc (4) - View/ViewEngine

    原文:返璞归真 asp.net mvc (4) - View/ViewEngine [索引页] [源码下载] 返璞归真 asp.net mvc (4) - View/ViewEngine 作者:web ...

  5. 返璞归真 asp.net mvc (10) - asp.net mvc 4.0 新特性之 Web API

    原文:返璞归真 asp.net mvc (10) - asp.net mvc 4.0 新特性之 Web API [索引页][源码下载] 返璞归真 asp.net mvc (10) - asp.net ...

  6. [转]ASP.NET MVC 5 - 添加一个模型

    在本节中,您将添加一些类,这些类用于管理数据库中的电影.这些类是ASP.NET MVC 应用程序中的"模型(Model)". 您将使用.NET Framework 数据访问技术En ...

  7. 返璞归真 asp.net mvc (13) - asp.net mvc 5.0 新特性

    [索引页][源码下载] 返璞归真 asp.net mvc (13) - asp.net mvc 5.0 新特性 作者:webabcd 介绍asp.net mvc 之 asp.net mvc 5.0 新 ...

  8. 返璞归真 asp.net mvc (7) - asp.net mvc 3.0 新特性之 Controller

    原文:返璞归真 asp.net mvc (7) - asp.net mvc 3.0 新特性之 Controller [索引页][源码下载] 返璞归真 asp.net mvc (7) - asp.net ...

  9. 返璞归真 asp.net mvc (8) - asp.net mvc 3.0 新特性之 Model

    原文:返璞归真 asp.net mvc (8) - asp.net mvc 3.0 新特性之 Model [索引页][源码下载] 返璞归真 asp.net mvc (8) - asp.net mvc ...

随机推荐

  1. svn简介与使用

    本文简单介绍windows下svn服务器与客户端软件的简单应用. 其中,svn服务器用于储存和管理代码,相当与文本服务器的作用(多版本控制等功能),同时分配用户代码的访问与使用权限. 客户端软件 用于 ...

  2. Java提供的enum详解

    今天第一天看<<Effective Java>>,看了第六章的第一条就是全书的第30条--用enum代替int常量. 1.第一次知道原来enum也可以像class那样拥有成员函 ...

  3. Linux进程同步之记录锁(fcntl)

    记录锁相当于线程同步中读写锁的一种扩展类型,可以用来对有亲缘或无亲缘关系的进程进行文件读与写的同步,通过fcntl函数来执行上锁操作.尽管读写锁也可以通过在共享内存区来进行进程的同步,但是fcntl记 ...

  4. c++进阶

    对网络编程/多线程/系统编程有一定了解:4:对ngnix,redis,memcache有一定了解:5:有高并发服务开发经验优先: 因为C/C++在嵌入式.移动互联网.物联网有很大的优势,有很多人就靠一 ...

  5. Android Ant打包笔记

    本文文档的下载地址(Word版):http://download.csdn.net/detail/yangwei19680827/7250711 Android Ant 打包 网上找了ant打包的资料 ...

  6. Conversion to Dalvik format failed with error 1

    主要和添�的第三方的包有关系. ======================================= 出现,Conversion to Dalvik format failed with e ...

  7. Screwturn搭建企业内部wiki

    企业内部WIKI搭建 本文所使用的是Screwturn 基于asp.net webform和Sql server的. 仅仅要把本文资源下载下来,直接用IIS部署,然后更改web.config的conn ...

  8. Android kxml解析WBXML

     WAP Binary XML定义好XML片断表述出同步server地址.远程数据库名称.登录账号等等内容一.两种訪问方法: 眼下的kxml支持两种wap格式:WBXML/WML. 而有两种方法将解析 ...

  9. Custom Media Player in WPF (Part 1)

    First of all I would like to welcome everyone to my new blog and wish you all a happy new year… Thro ...

  10. struts2 Session拦截器

    一:struts2简介 二:拦截器