ASP.NET MVC Preview 5 演示Demo #6 实现MvcContrib的Html.CheckBoxList()应用
ASP.NET MVC Preview 5 演示Demo #6 实现MvcContrib的Html.CheckBoxList()应用
ASP.NET MVC Preview 5 演示Demo系列: http://mike108mvp.cnblogs.com
ASP.NET MVC QQ交流群1:1215279 QQ交流群2:1214648 QQ交流群3:47788243(可容纳500人)
This Mvc Demo #6 demonstrates how to use the open source project MvcContrib's Html.FormHelper().CheckBoxList().
Hope this helps, enjoy it.
Download the Code:https://files.cnblogs.com/mike108mvp/Mike108Demo06.rar
这个演示项目实现了在ASP.NET MVC中使用开源项目MvcContrib的Html.FormHelper().CheckBoxList()控件。
MvcContrib是一个开源的ASP.NET MVC 扩展功能项目。MvcContrib官方网站:http://www.codeplex.com/MVCContrib/
开发环境:Visual Studio 2008 SP1 + ASP.NET MVC Preview 5 + Linq To Sql + SQL Server 2005
ASP.NET MVC Preview 5 下载地址: http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16775
【Step By Step 操作步骤】
1、SQL Server 2005 执行下面的Sql查询脚本。该Sql脚本将生成一个新的mike108mvp数据库,里面包含5个表User、UserType、Product、Order、OrderItem。
注意:该Demo #6数据库脚本与之前的脚本不同。无论你是否执行过Demo #6之前的脚本,都需要重新执行这个新的数据库脚本。【ok】
/**//****** 先删除再重新生成数据库 ******/
USE [master]
GO
IF EXISTS (SELECT name FROM sys.databases WHERE name = N'mike108mvp')
DROP DATABASE [mike108mvp]
CREATE DATABASE [mike108mvp]
GO
/**//****** 生成表结构 ******/
USE [mike108mvp]
GO
/**//****** 对象: Table [dbo].[UserType] 脚本日期: 09/15/2008 15:53:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserType](
[TypeId] [int] NOT NULL,
[TypeName] [nvarchar](50) NULL,
CONSTRAINT [PK_UserType] PRIMARY KEY CLUSTERED
(
[TypeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
/**//****** 对象: Table [dbo].[User] 脚本日期: 09/15/2008 15:54:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[User](
[UserId] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](50) NULL,
[TypeId] [int] NOT NULL,
[Sex] [bit] NOT NULL,
[Age] [int] NULL,
[Career] [nvarchar](50) NULL,
[FileName] [nvarchar](200) NULL,
CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
(
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Id' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'User', @level2type=N'COLUMN',@level2name=N'UserId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'姓名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'User', @level2type=N'COLUMN',@level2name=N'UserName'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'分类' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'User', @level2type=N'COLUMN',@level2name=N'TypeId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'性别' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'User', @level2type=N'COLUMN',@level2name=N'Sex'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'年龄' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'User', @level2type=N'COLUMN',@level2name=N'Age'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'职业' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'User', @level2type=N'COLUMN',@level2name=N'Career'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'附件名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'User', @level2type=N'COLUMN',@level2name=N'FileName'
GO
ALTER TABLE [dbo].[User] WITH CHECK ADD CONSTRAINT [FK_User_UserType] FOREIGN KEY([TypeId])
REFERENCES [dbo].[UserType] ([TypeId])
GO
ALTER TABLE [dbo].[User] CHECK CONSTRAINT [FK_User_UserType]
/**//****** Object: Table [dbo].[Product] Script Date: 09/26/2008 17:11:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Product](
[ProductId] [int] IDENTITY(1,1) NOT NULL,
[ProductName] [nvarchar](50) NULL,
[Price] [money] NULL,
CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
[ProductId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
/**//****** Object: Table [dbo].[Order] Script Date: 09/26/2008 17:12:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Order](
[OrderId] [int] IDENTITY(1,1) NOT NULL,
[OrderName] [nvarchar](50) NOT NULL,
[OrderTime] [datetime] NOT NULL,
[UserId] [int] NOT NULL,
[ProductList] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Order] PRIMARY KEY CLUSTERED
(
[OrderId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'本订单采购的产品Id 逗号隔开' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Order', @level2type=N'COLUMN',@level2name=N'ProductList'
GO
ALTER TABLE [dbo].[Order] WITH CHECK ADD CONSTRAINT [FK_Order_User] FOREIGN KEY([UserId])
REFERENCES [dbo].[User] ([UserId])
GO
ALTER TABLE [dbo].[Order] CHECK CONSTRAINT [FK_Order_User]
/**//****** Object: Table [dbo].[OrderItem] Script Date: 09/26/2008 17:13:17 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[OrderItem](
[OrderItemId] [int] IDENTITY(1,1) NOT NULL,
[UserId] [int] NOT NULL,
[OrderId] [int] NOT NULL,
[ProductId] [int] NOT NULL,
[UnitPrice] [money] NOT NULL,
[Quantity] [int] NOT NULL,
CONSTRAINT [PK_OrderItem] PRIMARY KEY CLUSTERED
(
[OrderItemId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'订单详情' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderItem', @level2type=N'COLUMN',@level2name=N'OrderItemId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'订单Id' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderItem', @level2type=N'COLUMN',@level2name=N'OrderId'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'产品单价' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderItem', @level2type=N'COLUMN',@level2name=N'UnitPrice'
GO
EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'产品数量' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'OrderItem', @level2type=N'COLUMN',@level2name=N'Quantity'
GO
ALTER TABLE [dbo].[OrderItem] WITH CHECK ADD CONSTRAINT [FK_OrderItem_Order] FOREIGN KEY([OrderId])
REFERENCES [dbo].[Order] ([OrderId])
GO
ALTER TABLE [dbo].[OrderItem] CHECK CONSTRAINT [FK_OrderItem_Order]
GO
ALTER TABLE [dbo].[OrderItem] WITH CHECK ADD CONSTRAINT [FK_OrderItem_Product] FOREIGN KEY([ProductId])
REFERENCES [dbo].[Product] ([ProductId])
GO
ALTER TABLE [dbo].[OrderItem] CHECK CONSTRAINT [FK_OrderItem_Product]
GO
ALTER TABLE [dbo].[OrderItem] WITH CHECK ADD CONSTRAINT [FK_OrderItem_User] FOREIGN KEY([UserId])
REFERENCES [dbo].[User] ([UserId])
GO
ALTER TABLE [dbo].[OrderItem] CHECK CONSTRAINT [FK_OrderItem_User]
/**//****** 脚本结束 ******/
2、下载本演示源码:https://files.cnblogs.com/mike108mvp/Mike108Demo06.rar
Visual Studio 2008 双击打开下载的演示源码中的 Mike108Demo.sln 解决方案文件,按F5运行。【ok】
3、运行后,点击页面右上角的“采购”链接。打钩选中要采购的产品,输入采购数量(默认采购数量为1),点击“批量采购”。【ok】
4、点击订单列表中的“订单明细”链接,可以在右边显示该订单的明细列表。【ok】
5、UsersController.cs 代码:【ok】
{
Mike108mvpDataContext db = new Mike108mvpDataContext();
Demo #1 CRUD操作#region Demo #1 CRUD操作
public ActionResult UserAdd()
{
return View(@"Add");
}
public ActionResult UserCreate()
{
if (Request.HttpMethod != "POST")
{ return View(@"Add"); }
User model = new User();
UpdateModel(model, Request.Form.AllKeys);
db.Users.InsertOnSubmit(model);
db.SubmitChanges();
return RedirectToAction("UserList");
}
public ActionResult UserEdit(int userId)
{
User model = db.Users.FirstOrDefault(e => e.UserId == userId);
return View(@"Edit", model);
}
public ActionResult UserUpdate(int userId)
{
if (Request.HttpMethod != "POST")
{ return RedirectToAction("UserEdit", new { userId = userId }); }
User model = db.Users.FirstOrDefault(e => e.UserId == userId);
UpdateModel(model, Request.Form.AllKeys);
db.SubmitChanges();
return RedirectToAction("UserList");
}
public ActionResult UserDetail(int userId)
{
User model = db.Users.FirstOrDefault(e => e.UserId == userId);
return View(@"Detail", model);
}
public ActionResult UserDelete(int userId)
{
User model = db.Users.FirstOrDefault(e => e.UserId == userId);
db.Users.DeleteOnSubmit(model);
db.SubmitChanges();
return RedirectToAction("UserList");
}
public ActionResult UserList1()
{
if (db.Users.Count() == 0 || db.UserTypes.Count() == 0)
{
return RedirectToAction("DataReset");
}
ViewData["UserList"] = db.Users.ToList();
return View(@"List");
}
#endregion
Demo #1 数据重置#region Demo #1 数据重置
public ActionResult DataReset()
{
//批量添加用户分类
if (db.UserTypes.Count() == 0)
{
List<UserType> userTypelist = new List<UserType>
{
new UserType { TypeId=1, TypeName = "总统" },
new UserType { TypeId=2, TypeName = "独裁者" },
new UserType { TypeId=3, TypeName = "S.H.E" },
new UserType { TypeId=4, TypeName = "小虎队" },
new UserType { TypeId=5, TypeName = "NBA" },
new UserType { TypeId=6, TypeName = "科学家" }
};
db.UserTypes.InsertAllOnSubmit(userTypelist);
db.SubmitChanges();
}
//批量删除用户
//List<User> oldList = db.Users.ToList();
//db.Users.DeleteAllOnSubmit(oldList);
//批量添加用户
if (db.Users.Count() == 0)
{
List<User> userlist = new List<User>
{
new User { UserName = "孙中山", TypeId=1, Sex=true, Age = 53, Career = "中国总统" },
new User { UserName = "蒋中正", TypeId=1, Sex=true, Age = 36, Career = "中国总统" },
new User { UserName = "小布什", TypeId=1, Sex=true, Age = 61, Career = "美国总统" },
new User { UserName = "列宁", TypeId=2, Sex=true, Age = 49, Career = "邪恶苏联" },
new User { UserName = "斯大林", TypeId=2, Sex=true, Age = 49, Career = "邪恶苏联" },
new User { UserName = "Selina", TypeId=3, Sex=false, Age = 26, Career = "女艺人" },
new User { UserName = "Hebe", TypeId=3, Sex=false, Age = 25, Career = "女艺人" },
new User { UserName = "Ella", TypeId=3, Sex=false, Age = 26, Career = "女艺人" },
new User { UserName = "吴奇隆", TypeId=4, Sex=true, Age = 34, Career = "男艺人" },
new User { UserName = "苏有朋", TypeId=4, Sex=true, Age = 33, Career = "男艺人" },
new User { UserName = "陈志朋", TypeId=4, Sex=true, Age = 35, Career = "男艺人" },
new User { UserName = "乔丹", TypeId=5, Sex=true, Age = 39, Career = "球星" },
new User { UserName = "皮蓬", TypeId=5, Sex=true, Age = 38, Career = "球星" },
new User { UserName = "罗德曼", TypeId=5, Sex=true, Age = 37, Career = "球星" },
new User { UserName = "姚明", TypeId=5, Sex=true, Age = 27, Career = "球星" },
new User { UserName = "易建联", TypeId=5, Sex=true, Age = 20, Career = "球星" },
new User { UserName = "科比", TypeId=5, Sex=true, Age = 29, Career = "球星" },
new User { UserName = "麦蒂", TypeId=5, Sex=true, Age = 33, Career = "球星" },
new User { UserName = "艾弗森", TypeId=5, Sex=true, Age = 29, Career = "球星" },
new User { UserName = "詹姆斯", TypeId=5, Sex=true, Age = 29, Career = "球星" },
new User { UserName = "加内特", TypeId=5, Sex=true, Age = 32, Career = "球星" },
new User { UserName = "比尔盖茨", TypeId=6, Sex=true, Age = 62, Career = "微软老大" },
new User { UserName = "Scott Guthrie", TypeId=6, Sex=true, Age = 33, Career = "ASP.NET Leader" }
};
db.Users.InsertAllOnSubmit(userlist);
db.SubmitChanges();
}
//批量添加产品
if (db.Products.Count() == 0)
{
List<Product> productlist = new List<Product>
{
new Product { ProductName="苹果", Price=(decimal)1.5 },
new Product { ProductName="梨子", Price=(decimal)2.0 },
new Product { ProductName="柑橘", Price=(decimal)0.5 },
new Product { ProductName="荔枝", Price=(decimal)1.8 },
new Product { ProductName="菠萝", Price=(decimal)3.0 },
new Product { ProductName="草莓", Price=(decimal)3.5 },
new Product { ProductName="樱桃", Price=(decimal)6.0 },
new Product { ProductName="橄榄", Price=(decimal)8.5 },
new Product { ProductName="芒果", Price=(decimal)9.0 }
};
db.Products.InsertAllOnSubmit(productlist);
db.SubmitChanges();
}
return RedirectToAction("UserList");
}
#endregion
Demo #2 微软Membership权限#region Demo #2 微软Membership权限
[Authorize] //登陆后才能查看
public ActionResult UserMembership()
{
User model = db.Users.FirstOrDefault(e => e.UserName == "孙中山");
return View(@"Detail", model);
}
#endregion
Demo #3 实现MVC批量上传文件#region Demo #3 实现MVC批量上传文件
public ActionResult Upload()
{
return View(@"Upload");
}
public ActionResult UploadFiles()
{
var r = new List<MikeUploadFile>();
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "Upload\\", Path.GetFileName(hpf.FileName));
hpf.SaveAs(savedFileName);
r.Add(new MikeUploadFile()
{
Name = savedFileName,
Length = hpf.ContentLength
});
}
return View(@"Upload", r);
}
#endregion
Demo #4 实现RadioButtonList和DropDownList应用#region Demo #4 实现RadioButtonList和DropDownList应用
// Demo #4 没有加入新的Controller代码
#endregion
Demo #5 实现MikePager数据分页和GridView控件#region Demo #5 实现MikePager数据分页和GridView控件
public ActionResult UserList(int? pageIndex, int? pageSize)
{
if (db.Users.Count() == 0 || db.UserTypes.Count() == 0)
{
return RedirectToAction("DataReset");
}
int pIndex = pageIndex ?? 1;
int pSize = pageSize ?? 10;
GridViewData<User> gridViewData = new GridViewData<User>();
gridViewData.PagedList = db.Users.OrderBy(e => e.UserId).ToPagedList<User>(pIndex, pSize);
return View(@"List", gridViewData);
}
#endregion
Demo #6 实现MvcContrib的Html.CheckBoxList应用#region Demo #6 实现MvcContrib的Html.CheckBoxList应用
[AcceptVerbs("GET")]
public ActionResult BuyProduct()
{
List<Product> productList = db.Products.ToList();
ViewData["products"] = productList;
return View(@"BuyProduct");
}
[AcceptVerbs("Post")]
public ActionResult BuyProductSave()
{
string[] selectedList = Request.Form.GetValues("productList"); //被选中的项
int selectedAmount = Request.Form.GetValues("productList").Length; //被选中项的个数
//本次订单的产品Id列表,用逗号隔开保存在Order表的ProductList字段中
string buyProductIds = "";
StringBuilder sb = new StringBuilder();
foreach (string productId in selectedList)
{
sb.Append(productId + ",");
}
if (sb.Length > 1)
{
buyProductIds = sb.ToString(0, sb.Length - 1);
}
//假设当前登陆用户是Selina
User currentUser = db.Users.FirstOrDefault(e => e.UserName == "Selina");
//添加一个订单到Order表
Order order = new Order();
order.OrderName = currentUser.UserName + " 订单";
order.OrderTime = DateTime.Now;
order.UserId = currentUser.UserId;
order.ProductList = buyProductIds;
db.Orders.InsertOnSubmit(order);
db.SubmitChanges();
//批量添加多个订单明细到OrderItem表
foreach (string productId in selectedList)
{
OrderItem orderItem = new OrderItem();
orderItem.OrderId = order.OrderId;
orderItem.UserId = currentUser.UserId;
orderItem.ProductId = int.Parse(productId);
int quantity = int.Parse(Request.Form["Quantity" + productId]); //采购数量
orderItem.Quantity = quantity;
Product product = db.Products.FirstOrDefault(e => e.ProductId == int.Parse(productId));
orderItem.UnitPrice = product.Price.Value;
db.OrderItems.InsertOnSubmit(orderItem);
}
db.SubmitChanges();
return RedirectToAction("OrderList");
}
public ActionResult OrderList(int? pageIndex, int? pageSize, int? orderId)
{
int pIndex = pageIndex ?? 1;
int pSize = pageSize ?? 10;
//订单列表
GridViewData<Order> gridViewData = new GridViewData<Order>();
gridViewData.PagedList = db.Orders.OrderByDescending(e => e.OrderId).ToPagedList(pIndex, pSize);
//订单明细列表
GridViewData<OrderItem> orderItemGridViewData = new GridViewData<OrderItem>();
if (!string.IsNullOrEmpty(Request.QueryString["orderId"]))
{
int id = int.Parse(Request.QueryString["orderId"]);
orderItemGridViewData.PagedList = db.OrderItems.Where(e => e.OrderId == id).OrderBy(e => e.OrderItemId).ToPagedList(pIndex, pSize);
}
else
{
orderItemGridViewData.PagedList = db.OrderItems.OrderBy(e => e.OrderItemId).ToPagedList(pIndex, 100);
}
ViewData["OrderItemList"] = orderItemGridViewData;
return View(@"~/Views/Users/OrderList.aspx", gridViewData);
}
#endregion
}
6、Views/Users/BuyProduct.aspx 产品采购页面,Views/Users/OrderList.aspx 订单列表与订单明细页面。【ok】
7、MvcContrib是一个开源的ASP.NET MVC扩展功能项目。如果你要新建一个项目来使用MvcContrib的一些功能。则只需复制MvcContrib项目的MvcContrib.dll文件到新项目的Bin目录中。
然后打开web.config添加命名空间:<add namespace="MvcContrib.UI.Html"/> 【ok】
Download the Code:https://files.cnblogs.com/mike108mvp/Mike108Demo06.rar
ASP.NET MVC Preview 5 演示Demo系列: http://mike108mvp.cnblogs.com
Demo #1 实现CRUD增删查改:http://www.cnblogs.com/mike108mvp/archive/2008/08/31/1280689.html
Demo #2 实现Membership角色权限控制:http://www.cnblogs.com/mike108mvp/archive/2008/09/03/1283432.html
Demo #3 实现MVC批量上传文件:http://www.cnblogs.com/mike108mvp/archive/2008/09/04/1284087.html
Demo #4 实现RadioButtonList与DropDownList应用:http://www.cnblogs.com/mike108mvp/archive/2008/09/15/1291153.html
Demo #5 实现MikePager数据分页和GridView控件:http://www.cnblogs.com/mike108mvp/archive/2008/09/19/1294079.html
posted on 2008-09-27 14:55 mike108mvp 阅读(6543) 评论(1) 编辑 收藏 举报