Introduction
This article describes the calling of the partial view on a conditional basis. The partial view is used for displaying the information that depends on the condition. The partial view works on conditions.
The following is the procedure for creating the application.
Step 1. First, we create a Web API application as in the following.
- Start Visual Studio 2013.
- From the start window select "New Project".
- From the new project window select "Installed" -> "Visual C#" -> "Web" -> "Visual Studio 2012".
- Select "ASP.NET MVC 4 Web Application" and click the "OK" button.
- From the "MVC4 project" window select "Web API".
- Click on the "OK" button.
Step 2. Now in the "HomeController" add the code. This file exists.
- In the "Solution Explorer".
- Expand the "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 ViewAPI.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string viewpage)
{
if (viewpage == "1")
{
ViewBag.Page = "1";
}
else if (viewpage == "2")
{
ViewBag.Page = "2";
}
return View();
}
}
}
Step 3. Now create a Partial View.
- In the Controller.
- Right-click on the "Index".
- Click on "Add View".
- Change the name of the View to "ViewPage1".
- Click the "Add" Button.
Write this line of code.
@{
ViewBag.Title = "ViewPage1";
}
<h2>ViewPage1 is Displayed</h2>
In the same procedure create another partial view and provide these lines of code for it.
@{
ViewBag.Title = "ViewPage2";
}
<h2>ViewPage2 is displayed</h2>
Step 4. In the View provide the following.
- In the "Solution Explorer".
- Expand the "Views folder".
- Select "Home" -> "Index. cshtml".
Add the following code.
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm("Index", "Home"))
{
<select name="viewpage">
<option value="1"> View Page 1</option>
<option value="2"> View Page 2</option>
</select>
<br /><br />
<input type="submit" value="Submit" />
if (ViewBag.Page == "1")
{
@Html.Partial("ViewPage1");
}
else if (ViewBag.Page == "2")
{
@Html.Partial("ViewPage2");
}
}
Step 5. Execute the application.
Click on the "Submit" button.
Select the ViewPage2 from the dropdown list and click on the "Submit" button.