In today's article I will show you how can render a PartialView in asp.net core mvc using model class property with c#.net. Here we will use asp.net core 10 mvc. Here we will access or render the partial view from controller and display the assigned or passed value of partialview to parent view. So for this article we will create a new asp.net core 10 mvc application and add a model class file. In this file consider an employee model class file.
public class EmployeeModel
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
In controller we will an IActionResult method as shown below. In this code we will create the object of model class and assign some sample value and pass to view as shown below.
public IActionResult Index()
{
EmployeeModel employeeModel = new EmployeeModel()
{
EmployeeId = 1,
FirstName = "John",
LastName = "Doe",
Email = "jd@testemail.com"
};
return View(employeeModel);
}
In above code i have created object of EmployeeModel class and add a value. This value we will display in view by rendering the partialview. There are 4 days we are going to discuss here by which we can render the partial view.
There are 4 ways by which we can render partial view Html.Partial, Html.RenderPartial, Html.PartialAsync, Html.RenderPartialAsync. Here is the detail.
Now let's create the view page and render the values.
@model EmployeeModel
<p>
<h1>Employee Details</h1>
Name: @Model.FirstName @Model.LastName <br />
Employee Id: @Model.EmployeeId <br />
Email: @Model.Email <br />
</p>
Above code is for the partialview. Here we are displaying the value form the model class. Now let's create the view and render the partial view.
Partial
@model EmployeeModel
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
@Html.Partial("_MyPartialView", Model)
</div>
RenderPartial
@model EmployeeModel
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
@{
Html.RenderPartial("_MyPartialView", Model);
}
</div>
PartialAsync
@model EmployeeModel
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
@await Html.PartialAsync("_MyPartialView", Model)
</div>
RenderPartialAsync
@model EmployeeModel
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
@{
await Html.RenderPartialAsync("_MyPartialView", Model);
}
</div>
In above code I have shown the example of rendering the value. Now let's run the code and check the output.