ASP.NET MVC Razor pass model to layout

Các  bước thực hiện:

  1. 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.
  2. Trong hàm dựng (Constructor của Controller), khởi tạo dữ liệu cho thuộc tính đó
  3. Gán cho ViewData hoặc ViewBag
  4. 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.