Jiro Laboratory

C#、ASP.NET、JavaScript、Androidとか

Layout を変更する4種類の方法(ASP.NET MVC)

Different ways of rendering layouts in Asp.Net MVC
こちらの内容を日本語で要約しました。
引用元とは異なりますが、ここでは優先順位の高い順に記載します。

方法1 ActionResult(ViewResult)で指定する

public ActionResult Index()
{
    return View("Index", "_AdminLayout");
}

方法2 View で指定する

@{
  Layout = "~/Views/Shared/_AdminLayout.cshtml";
}

方法3 Views 以下の各フォルダに _ViewStart.cshtml を配置する

コントローラ単位に指定したい場合に使えそうです。

@{
  Layout = "~/Views/Shared/_AdminLayout.cshtml";
}

方法4 Views フォルダ直下の _ViewStart.cshtml で切り替える

@{
  var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();

  string layout = "";
  if (controller == "Admin")
  {
    layout = "~/Views/Shared/_AdminLayout.cshtml";
  }
  else
  {
    layout = "~/Views/Shared/_Layout.cshtml";
  }
  Layout = layout;
}