Tạo Model
Trong folder Models, tạo 1 class Product
Product.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ListProducts.Models
{
public class Product
{
private int _Id;
public int Id { get; set; }
private string _Name;
public string Name { get;set; }
}
}
Tạo controller
Tạo 1 controller mới hoặc trong controller Home, xóa hết tất cả các ActionResult mặc định, chỉ chừa lại 1 phương thức ActionResult là Index và tạo 1 ActionResult mới là Details
HomeController.cs
using ListProducts.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ListProducts.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
List<Product> products = new List<Product>()
{
new Product() { Id = 1, Name = "TV Sony" },
new Product() { Id = 2, Name = "Máy giặt Elextrolux" },
new Product() { Id=3,Name="NGỌC NHƯ Ý"},
new Product() { Id=4,Name="Trái tim công chúa"}
};
ViewBag.Products = products;
return View();
}
public ActionResult Details(int id)
{
List<Product> products = new List<Product>()
{
new Product() { Id = 1, Name = "TV Sony" },
new Product() { Id = 2, Name = "Máy giặt Elextrolux" },
new Product() { Id=3,Name="NGỌC NHƯ Ý"},
new Product() { Id=4,Name="Trái tim công chúa"}
};
Product matchingProduct = null;
foreach (Product product in products)
{
if (product.Id==id)
{
matchingProduct = product;
}
}
ViewBag.MatchingProduct= matchingProduct;
return View();
}
}
}
Tạo View
Trong folder Views, xóa folder Home đi, tạo View Index và Details
Index.cshtml
Code Index.cshtml
Details.cshtml
@{
ViewBag.Title = "TIKI - Mua hàng Online giá tốt, chất lượng, ship nhanh";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2 class="justify-content-center">CHI TIẾT SẢN PHẨM</h2>
<table class="table table-hove">
<tr>
<th>Product ID</th>
<td>@ViewBag.MatchingProduct.Id</td>
</tr>
<tr>
<th>Product Name</th>
<td>@ViewBag.MatchingProduct.Name</td>
</tr>
</table>
Tạo layout chung
Trong folder Shared trong folder Views, xóa file _Layout.cshtml mặc định để tạo Layout cho riêng mình
Chuột phải vào folder Shared -> chọn Add -> chọn MVC 5 Layout Page (Razor) -> Đặt tên là _Layout.cshtml
_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="/redirect?Id=9fLRaWQliBbz0ECLj4fqtEVVEaknSDhDxHclZjypxm4K7BtEopPujLJ6oDaqg5Cg" rel="stylesheet" type="text/css" />
<title>@ViewBag.Title</title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-2 text-white" style="background-color:aquamarine; min-height:1050px; padding:0">
<ScrollViewer>
@Html.ActionLink("Danh sách sản phẩm","Index","Home")
</ScrollViewer>
</div>
<div class="col-md-10" style="min-height:610px">
@RenderBody()
</div>
</div>
</div>
</body>
</html>
Hay