Các bước thực hiện:
- Add thuộc tính vào controller hoặc Base controller, ví dụ LayoutViewModel hoặc bất kỳ tên gì bạn muốn.
- Trong hàm dựng (Constructor của Controller), khởi tạo dữ liệu cho thuộc tính đó
- Gán cho ViewData hoặc ViewBag
- Trong Layout, ép kiểu hoặc sử dụng dữ liệu đó một cách phù hợp
Ví dụ Controller:
public class MyController : Controller
{
public DataTable LayoutViewModel { get; set; }
public MyController()
{
this.LayoutViewModel = new LayoutViewModel();
this.LayoutViewModel = new LoadDataTable();
this.ViewData["LayoutViewModel"] = this.LayoutViewModel;
}
}
Trong Layout Page
@{
var viewModel = (DataTable)ViewBag.LayoutViewModel;
}
Sau khi chúng ta đã có biến viewModel chưa dữ liệu cần lấy, lúc đó kết gán hoặc hiển thị theo chúng ta muốn.