1. 添加NorthWind.dbml对象
2. HomeController代码:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
public ActionResult ProductCategory()
{
NorthWindDataContext db=new NorthWindDataContext();
var model = new ProductModel();
model.category = db.Categories;
model.products = db.Products;
return View(model);
}
public ActionResult Categories()
{
NorthWindDataContext db=new NorthWindDataContext();
var model = db.Categories;
return View(model);
}
}
public class ProductModel
{
public IEnumerable<Category> category;
public IEnumerable<Product> products;
}
3. ProductCategory页面
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MVCDemo1.Controllers.ProductModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
ProductCategory
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>
ProductCategory</h2>
<table>
<tr>
<th>
</th>
</tr>
<% foreach (var item in Model.category)
{ %>
<tr>
<td>
<%:item.CategoryName %><br />
<% foreach (var item1 in Model.products)
{%>
<% if (item1.CategoryID == item.CategoryID)
{%>
<%:item1.ProductName%>
<% }
} %>
</td>
</tr>
<% } %>
</table>
</asp:Content>