ASP.NET MVC SportStore 购物网示例(1)
Download!!!
介绍
使用一下技术创建简单的购物网演练。
ASP.NET MVC Framework
Castle-Windsor-2.0
NUnit
创建项目
创建空的解决方案 SportStore ,向解决方案添加:
项目名称 |
项目类型 |
|
DomainModel |
C# class library |
|
WebUI |
ASP.NET MVC2 Web Application |
不包含 Unit Test |
Tests |
C# class library |
单元测试 |
删除WebUI自动生成的文件:
目录 |
文件 |
Controllers |
* |
Views/Account |
* |
Views/Home |
* (保留index) |
Views/Shared |
Error.aspx LogOnUserControl.ascx |
为WebUI添加DomainModel的引用,编译项目。
DomainModel
DomainModel是程序的核心,从这里开发创建实体类Product。
namespace DomainModel.Entities
{
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
}
Abstract Repository
namespace DomainModel.Abstract
{
public interface IProductsRepository
{
IQueryable<Product> Products { get; }
}
}
Fake Repository
namespace DomainModel.Concrete
{
public class FakeProductsRepository : IProductsRepository
{
// Fake hard-coded list of products
private static IQueryable<Product> fakeProducts = new List<Product> {
new Product { Name = "Football", Price = 25 },
new Product { Name = "Surf board", Price = 179 },
new Product { Name = "Running shoes", Price = 95 }
}.AsQueryable();
public IQueryable<Product> Products
{
get { return fakeProducts; }
}
}
}
创建 Controller
创建ProductsController,返回一个数据列表
public class ProductsController : Controller
{
private IProductsRepository productsRepository;
public ProductsController()
{
// This is just temporary until we have more infrastructure in place
productsRepository = new FakeProductsRepository();
}
public ViewResult List()
{
return View(productsRepository.Products.ToList());
}
}
设置默认的路由(Route)
打开Global.asax.Cs, 修改代码如下:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Products", action = "List", id = "" } // Parameter defaults
);
}
右键点击List()创建一个视图(View)用来显示数据
注意:如果没有DomainModel.Entities.Product,需要先编译DomainModel。
编辑 代码如下:
<% foreach (var item in Model) { %>
<tr>
<td>
<%= Html.Encode(item.Name) %>
</td>
<td>
<%= Html.Encode(item.Description) %>
</td>
<td>
<%= Html.Encode(String.Format("{0:F}", item.Price)) %>
</td>
</tr>
<% } %>
最后打开 site.Master文件删除
<% Html.RenderPartial("LogOnUserControl"); %>
F5运行。
转载请注明出处! Author: im@xingquan.org