This article will show you how you can dynamically load the mvc
layout page on selection of dropdown value.
This article will help you on identifying or loading the master or
layout page on conditional bases using c#.net in asp.net mvc.
Some of my previous articles are as follows: Dynamic
Vertical Css Menu Using jQuery, Css and C#.net In Asp.net MVC, Responsive
Grid Design Example Using Css in Asp.Net MVC,HTML, Shopping
Cart Example to Drag and Drop Item in Cart In Asp.Net MVC Using jQuery, jQuery
Ajax Cascaded DropdownList in Asp.net MVC Using C#.Net, Ajax
Login Form Using jQuery in Asp.net MVC and C#.Net, Dynamic
Histogram Google Chart in asp.net MVC using C#.net, JavaScript, Password
Strength Validation in Asp.net MVC Using jQuery.
So for this article first we will create a new asp.net mvc
application and add a controller class file and add the below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication9.Controllers
{
public class HomeController
: Controller
{
//
// GET:
/Home/
public
ActionResult Index()
{
ViewBag.LayoutId = 1;
return
View();
}
[HttpPost]
public
ActionResult Index(int Layout)
{
ViewBag.LayoutId = Layout;
return
View();
}
}
}
|
In above I have shown get and post method. In post method I have
passed the dropdown list value as a value of layout page.
After this we will create two layout page by changing header
value.
LAYOUT1
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
</head>
<body>
<table width="100%" border="1">
<tr>
<td>
<h2>
LAYOUT HEADER 1</h2>
</td>
</tr>
<tr>
<td>
@RenderBody()
</td>
</tr>
</table>
</body>
</html>
|
LAYOUT2
<!DOCTYPE html>
<html>
<head>
<title>@ViewBag.Title</title>
</head>
<body>
<div>
<table width="100%" border="1">
<tr>
<td>
<h2>
LAYOUT HEADER 2</h2>
</td>
</tr>
<tr>
<td>
@RenderBody()
</td>
</tr>
</table>
</div>
</body>
</html>
|
Now create the view on action method and add the below code
in it.
@{
if
(ViewBag.LayoutId == 1)
{
ViewBag.Title = "Layout 1";
Layout = "../Shared/_Layout.cshtml";
}
else
{
ViewBag.Title = "Layout 2";
Layout = "../Shared/_LayoutPage1.cshtml";
}
}
@using
(Html.BeginForm("Index", "Home"))
{
<select name="Layout">
<option value="1">Layout 1</option>
<option value="2">Layout 2</option>
</select><br />
<input type="submit" value="Submit" />
}
|
In above code I have created a dropdown list in which I have
defined layout name. Now check the above part of the code. In this code I have
validate the viewbag value and on the bases of value I have changed the layout
page.
Now run the page to c heck the output.
Now run the page to c heck the output.
Now select layout2 and click on submit button. Just check the below image where i am capturing dropdown liat value and storing it in viewbag.
Now press F5 and check the final output.
0 comments:
Please let me know your view