Monday, 24 December 2018

Partial Views in MVC

Partial views in MVC are similar to user controls in asp.net web forms. We can keep all reusable view codes in partial views i.e when we are working in large application and Address field is used by multiple pages( Views), then instead of repeating the code in every page we can create a separate partial view and can call this view whenever it required.

A partial view must be kept in the Shared folder so that it can be accessed through the application. If you will keep partial view in a specific folder then that is available for that only. To render the partial view, we are using Partial() HTML helper method. It is an overloaded method and you can use it as per your requirement.

Below is the complete example of a partial view:

Add this class to the Model folder.

public class Address    {        public string StreetName { getset; }        public string LandMark { getset; }        public string CityName { getset; }        public string StateName { getset; }        public string CountryName { getset; }        public string pincode { getset; }     }

Add a partial view named _Address. Below are the code for this view.

@model IEnumerable<PartialViewTest.Models.Address> <h2>This is an example of Partial View</h2><p>    @Html.ActionLink("Create New""Create")</p><table class="table">    <tr>        <th>            @Html.DisplayNameFor(model => model.StreetName)        </th>        <th>            @Html.DisplayNameFor(model => model.LandMark)        </th>        <th>            @Html.DisplayNameFor(model => model.CityName)        </th>        <th>            @Html.DisplayNameFor(model => model.StateName)        </th>        <th>            @Html.DisplayNameFor(model => model.CountryName)        </th>        <th>            @Html.DisplayNameFor(model => model.pincode)        </th>        <th></th>    </tr> </table>

Call this partial view in any other view with @Html.Partial("_Address")
In our case, we called this in About view page.

@{    ViewBag.Title = "About";} @Html.Partial("_Address") 













Partial Views are of two types:

Static Partial View: Static Partial View is used to render the static data.
  • @{Html.RenderPartial(“_Address”);} - It will return the void. Displays the output on your view page.
  • @Html.Partial(“_Address”); - It will return MVC HTML string, you can store it in a particular variable.
Dynamic Partial View: Dynamic Partial Views are used to implement the dynamic data.
  • @{Html.RenderAction(“_Address”);} 
  • @Html.Action(“_Address”);- It will return MVC HTML string.

The above is an example of a static partial view. In the same manner, you can create as many as reusable components for your application.
 

No comments:

Post a Comment