재우니의 블로그

ASP.NET MVC 의 Layout.cshtml 에서 model 전달하기


asp.net mvc 에서는 view 의 shared 폴더에 _layout.cshtml 이 존재합니다. 이는 이전의 webform 의 master 와 비슷한 기능을 구성하고 있죠.

하지만 _layout.cshtml 에 model 을 넘기는 방법을 별로 추천하지는 않지만, controller 에서 _layout.cshtml 에 모델을 할당하여 컨트롤 하고자 할때 ViewData() 를 객체 할당하여 사용하는 방법이 존재합니다.


예를 들어보죠.


MainLayoutViewModel 은 model 로써 미리 사용할 필드를 만들어 놓으시고, MyController 라는 controller 에서 layout 에 사용할 오브젝트를 객체화 하여 ViewData() 에 담습니다. 매번 사용할 예정이니 생성자에서 구현한 부분입니다.



public class MyController : Controller
{
public MainLayoutViewModel MainLayoutViewModel { get; set; }

public MyController()
{
this.MainLayoutViewModel = new MainLayoutViewModel();//has property PageTitle
this.MainLayoutViewModel.PageTitle = "my title";

this.ViewData["MainLayoutViewModel"] = this.MainLayoutViewModel;
}

}


_Layout.cshtml 에서 객체를 받은 부분입니다. 형변환하여 객체에 할당하셔서 사용하시면 됩니다. 

주의할점은 꼭 해당 layout 를 사용할 경우, 위와 같이 객체 생성하지 않으면 오류 발생된다는 점 입니다.


@{
var viewModel = (MainLayoutViewModel)ViewBag.MainLayoutViewModel;
}



발췌 사이트 : https://stackoverflow.com/a/14882183