Introduction
This article shows how to change the layout page at runtime in the Web API. Here I will use a simple way to change the layout page.
The following is the procedure for creating the application.
Step 1
First create a Web API application as in the following:
- Start Visual Studio 2012.
- From the start window select "New Project".
- From the new project window select "Installed" -> "Visual C#" -> "Web".
- Select "ASP.NET MVC4 Web Application" and click the "Ok" button.
- From the "MVC4 Project" window select "Web API".
Step 2
Now in the controller we add some code as in the following:
- In the "Solution Explorer".
- Expand "Controller" folder.
- Select the "HomeController".
Add the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication9.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Layout = "~/Views/Shared/_LayoutPage1.cshtml";
return View();
}
[HttpPost]
public ActionResult Index(int id = 0)
{
ViewBag.Layout = "~/Views/Shared/_LayoutPage2.cshtml";
return View();
}
}
}
" ViewBag.Layout = "~/Views/Shared/_LayoutPage1.cshtml";" It specifies the path of the layout page1.cshtml. This call in the index.cshtml file when we execute the
application then the controller accesses the index file. The index file will show the layoutpage1.cshtml.
" ViewBag.Layout = "~/Views/Shared/_LayoutPage2.cshtml";" It tells the path of the layout page2.cshtml.
Step 3
Now add a LayoutPage.cshtml as in the following:
-
In the "Solution Explorer".
-
Expand the "Home" folder .
-
Right-click on the "Shared" -> "NewItem".
-
From new item window select "Installed" -> "VisualC#" -> "Web".
Add the following code:
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
</head>
<body>
<h2>This is the Layout page 1 </h2>
@RenderBody()
</body>
</html>
Step 4
Now add on more Layout Page.cshtml using the Step 3 procedure and add the following code:
<!DOCTYPE html><html>
<head>
<title>@ViewBag.Title</title>
</head>
<body>
<div>
<h2>Now You can see the Layout page 2</h2>
@RenderBody()
</div>
</body>
</html>
Step 5
In the View write some code as in the following:
- In the "Solution Explorer".
- Expand the "Views" folder.
- Select "Home" -> "Index.cshtml".
Add the following code:
@{
ViewBag.Title = "Index";
Layout = ViewBag.Layout;
}
<h2>Index</h2>
@using (Html.BeginForm("Index", "Home"))
{
<input type="submit" value="Click to Show LayoutPage2" />
}
Layout = ViewBag.Layout; it will call the layoutpage1.cshtml.
Step 6
Execute the application.
Click on the button; it then displays layoutpage2.cshtml.