ViewModel : 主要功能同時傳遞多個Model資料給View去顯示(傳統是一次只能傳遞一個Model資料給View顯示)
Step1:
在Models/ViewModels/ 下新增一個class,取名為:ProductCategoryViewModel.cs
public class ProductCategoryViewModel
{
public string Name { get; set; }
public string Book { get; set; }
public IEnumerable<Product> Product { get; set; }
public IEnumerable<Category> Category { get; set; }
}
}
Step2:
在Controller處理將資料傳到View
public ActionResult DemoViewModel()
{
return View(new ProductCategoryViewModel()
{
Name = "Melo",
Book = "ASP.NET MVC5",
Product = (from p in db.Products select p ).Take(10).ToList(),
Category = (from c in db.Categories select c).Take(10).ToList()
});
}
Step 3:
View顯示資料
@model CH_6_Practice.Models.ViewModels.ProductCategoryViewModel //記得引用Model才有智慧提示
@{
ViewBag.Title = "DemoViewModel";
}
<h2>DemoViewModel</h2>
<div>
<ul>
<li>@Model.Name</li>
<li>@Model.Book</li>
</ul>
<ul>
@foreach (var item in Model.Product)
{
<li>
@item.ProductName
</li>
}
</ul>
</div>
結果:
留言列表