Partial Views in MVC 5 with model binding


Q: What is partial view?

Ans: A partial view is a customized shared view, which can’t be served directly and can be used in other views. i.e Reusable custom view.

Q: What are the advantages with partial views?

Ans: 1. Sometimes you need to return just a piece and you can do it by a async request (using ajax). In these cases, you use an action that returns a Partial View.

2. Sometimes you need to implement an View that need to add a piece of code, so, you can render it using a Partial View.

3. Using partial views you can avoid code redundancy, i.e partial view are reusable

Q: How to Implement partial view in MVC

Ans: Here we will learn how to implement partial view in mvc with product catalog example.

let’s create product catalog data first

To reate product catalog data first create model as follows

Product Model
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Description { get; set; }
    public string ImagePath { get; set; }
}

Now create product catalog data

Products
public class Products
    {
        public List<Product> GetProducts()
        {
            return new List<Product>()
            {
                new Product{ Id=1,Name="F&D E200 (2.0 Channel)",Price=849,Description="F&D's E200 is an ergonomically designed sound bar which can conveniently get attached to your laptop or PC. You may place it in your purse and carry it to work without any excess weight or bulk.",ImagePath="/Content/Images/1.jpeg"},
                new Product{ Id=2,Name="F&D F203G Laptop Speakers (2.1 Channel)",Price=1289,Description="2.1 Channel Configuration,Subwoofer,Satellites,Wood Chassis",ImagePath="/Content/Images/2.jpeg"},
                //new Product{ Id=3,Name="Zebronics ZEB-S310 Club Wired Laptop Speakers (Black, 2…",Price=199,Description="Interface : usb, power input : (dc) 5v, frequency response : 20hz~20khz, driver unit : 2.5 x 2, output power : 3w x 2 (rms), s/n ratio : ?75 db, separation : ?65 db, impedance : 4 ?, dimensions : 70 x 70 x 187mm (wxhxd), input connectivity : 3.5 mm jack.",ImagePath="/Content/Images/3.jpeg"},
                new Product{ Id=4,Name="Portronics Pure Sound Portable Speaker (2.0 Channel)",Price=1165,Description="8 hrs Battery Life,Satellites",ImagePath="/Content/Images/4.jpeg"},
                new Product{ Id=5,Name="Philips DSP 2800 Home Audio (5.1 Channel)",Price=2980,Description="2.1 Channel Configuration,Subwoofer,Satellites,Wood Chassis",ImagePath="/Content/Images/5.jpeg"},
                //new Product{ Id=6,Name="Intex IT-880 s Wired Laptop Speakers (Black, 2.1 Channel)",Price=675,Description="2.1 Channel Stereo,Subwoofer,Speaker,Headphone Socket",ImagePath="/Content/Images/6.jpeg"},
                new Product{ Id=7,Name="JBL Charge Speaker (Single Unit Channel)",Price=6749,Description="20 W RMS Output Power,5.1 Home Audio,inch Woofer,inch Full Range,High Gloss Finish",ImagePath="/Content/Images/7.jpeg"},
                new Product{ Id=8,Name="Intex IT-880 S OS Wired Laptop Speakers (Black, 2.1 Cha…",Price=649,Description="150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device",ImagePath="/Content/Images/8.jpeg"},
                new Product{ Id=9,Name="Quantum QHM611 Wired Laptop Speakers (Black, 2.0 Channel)",Price=125,Description="150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device",ImagePath="/Content/Images/9.jpeg"},
                new Product{ Id=10,Name="Lenovo Portable Speaker M0520 (2.0 Channel)",Price=812,Description="150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device",ImagePath="/Content/Images/10.jpeg"}
            };
        }
    }

Now create one action method in controller as follows

Action Method
//
// GET: /PartialViews/
public ActionResult Index()
{
    Products products = new Products();
    return View(products.GetProducts());
}

 

Now add a view for the above action as follows

Right click on the action method and choose addview…

image

image

Click add to create view.

Write the following code in the created view

Product Catalog view
@model IEnumerable<MVCControls.Models.Product>
@{
    ViewBag.Title = "Partial views in MVC 5 || Chikkanti.wordpress.com";
    Layout = null;
}

<div style="padding: 5px;width:850px;margin:0px auto;">
    <h2>Partial views in MVC 5</h2>
    @foreach (var product in Model)
    {
        @Html.Partial("_ProductBox", product)
    }
</div>

 

In the above code @html.Partial is a helper class and we can use this to render our partial view. For this helper we are passing two parameters

1.”_ProductBox”: partial view name

2.product : Model for the partial view

Now let’s add the partial view in shared folder under views as follows

RightClick on Shared folder under views and choose add then view and fill the following details

image

image

After adding this partial view write the following code into it.

Partial View
@model MVCControls.Models.Product
<div class="products">
    <div>
        @Html.HiddenFor(m => m.Id)
    </div>
    <div>
        <img src="@Model.ImagePath" alt="@Model.Name" />
    </div>
    <div style="font-weight:bold;">
        @Html.LabelFor(m => m.Name):@Html.DisplayFor(m => m.Name)
    </div>
    <div style="color:green;">
        @Html.LabelFor(m => m.Price):RS.@Html.DisplayFor(m => m.Price)
    </div>
    <div style="color:brown;">
        @Html.LabelFor(m => m.Description):@Html.DisplayFor(m => m.Description)
    </div>
</div>
<style>
    .products {
        width: 150px;
        height: 200px;
        border: 1px #ffd926 solid;
        padding: 15px;
        float: left;
        overflow: hidden;
        overflow-wrap: break-word;
        overflow-y: hidden;
    }
</style>

 

Now Rebuild the application and run

image

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s