Tuesday, July 30, 2013

What Is MVC3 Partial View And Display Partial View On Conditional Bases

In this article i will give small description about mvc partial view and i will give a small example how you can load partial view based on condition.

In MVC Partial view act  as a container. It is used for displaying the information on conditional bases. 

So for this first create mvc3 web application and add a controller . In your controller add the below code.


 public ActionResult Index()
        {
            return View();
        }

Now create the index view. Now in your view add the below code.

@{
    ViewBag.Title = "Index";
}
@using (Html.BeginForm("Index", "Home"))
{
<select name="partialview">
    <option value="1">Partial View 1</option>
    <option value="2">Partial View 2</option>
</select>
    <br /><br />
    <input type="submit" value="Submit" />
    if (ViewBag.Page == "1")
    {
         @Html.Partial("PartialView1");
    }
    else if (ViewBag.Page == "2")
    {
         @Html.Partial("PartialView2");
    }
    }


In above code i have created dropdown in which i have defined the partial view name.
Now we will add two partial view. For this right click on the home view folder and click on add View .

add partial view

As you click on the view option below window will open.

add partial view

By clinking on the "create as partial view" you will be able to crate partial view. In same way create second partial view.

Now add the below code in partial view.

Partial View 1:

<h3>Partial View 1 Loadded Successfully</h3>


Partial View 2:

<h3>Partial View 2 Loadded Successfully</h3>


Now put the below code to complete the controller code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Partialview.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Index(string partialview)
        {
            if (partialview == "1")
            {
                ViewBag.Page = "1";
            }
            else if (partialview == "2")
            {
                ViewBag.Page = "2";
            }
            return View();
        }

    }
}


Now put the break point on the index post method and run the application.



Now click on the button you will hit the break point.

break point

Here you will get the selected value and you according to value will get stored in the viewbag. accordingly it on view partial view will load.

partial view

partial view

No comments:

Post a Comment