Saturday, May 18, 2019

Partial view with Model example in Asp.Net Core

In the previous post we saw a simple Partial View example, where a string from the partial view is displayed in the main view page. In this post we will improve this example to take a Model object and display the properties in the Model object.

When invoking a partial view from a main view, we can also pass a Model object to the partial view as follows. The properties in the passed model can be used in the HTML markup of the partial view.

@Html.Partial("_address", Model.EmpAddress)

In this example we will use an Employee model object, which contains an Address object embedded. We will pass the Address object to the partial view and display the properties in the Address object inside the partial view. Let us start by creating the following Employee model object.

    public class Employee
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public Address EmpAddress { get; set; }
    }

    public class Address
    {
        public string Street { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
    }

Next we will create a partial view _address.cshtml, which will use the Address object and display its properties as follows.

@model HelloMVC.Models.Address
<p>Employee Address (Content from Partial View)</p>
<p>Street: @Model.Street</p>
<p>City: @Model.City</p>
<p>Country: @Model.Country</p>

Finally we will create the parent view, and embed the partial view inside the main view as follows.

@model HelloMVC.Models.Employee
@{
    ViewData["Title"] = "Partical Views";
}

<p>Employee Details (Content from Main View)</p>
<p>Name: @Model.Name</p>
<p>Age: @Model.Age</p><br/>
@Html.Partial("_address", Model.EmpAddress)

Build and run the project, the output will be as follows.




Search Flipkart Products:
Flipkart.com

No comments: