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.

Step 2. Now in the "HomeController" add the code. This file exists.

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.

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.

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.

vie6.jpg

Click on the "Submit" button.

vie7.jpg

Select the ViewPage2 from the dropdown list and click on the "Submit" button.

vie8.jpg