Easy Steps to Implement Partial View in Asp.Net MVC

One of the best ways to implement a dynamic table without loading the whole page is by using Jquery Ajax request. Asp.Net MVC offers Ajax helpers to easily achieve this functionality. Partial View in Asp.Net MVC is one of its strengths. In this tutorial, we are going to use Ajax.Actionlink() to load Partial View in MVC.

Let’s start: 

Desired output: Partial View in Asp.Net

Partial View in Asp.Net

If this is your first time creating an MVC Web Application project refer to the thread below
How to start with ASP.NET MVC Web Application
ASP.NET MVC File structure

First, create a new model class for our model binding in creating a list of our sample data later in this tutorial. In my case, I name it as myModels.cs.

Partial View in Asp.Net

myModel

Declare following properties in your model class

Create a partial view inside View->Shared folder

Partial View in Asp.Net

• To add right-click on the Shared folder under Views and select Add->New Item and a new window will pop-up, select Web from the left pane of the window then select MVC 5 View Page(Razor) in the middle pane. Name your view, in my case I name it as _partialview.

Partial View in Asp.Net

This partial view will contain table design loaded to our main view

Code:

Bind this partial view with our model and receive the list pass from our controller using the code below.

• @model IEnumerable<UsingPartialView_MVC.Models.myModels>

And drop into C# code from the view and use for each loop to populate list to our table.
Full Code:

From your HomeController create a list of sample data

Partial View in Asp.Net

Code:

Then create a method that will pass the sample data above to our partial view and return partial view to our main view.

In your index create your main view declare this script to enable Jquery
• <script src=”//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js” type=”text/javascript”></script>
• <script src=”/Scripts/jquery.unobtrusive-ajax.js” type=”text/javascript”></script>

To install jquery.unobstrusive-ajax.js used NuGet Package manager console. To open NuGet Console navigate to tools->NuGet Package Manager->Package Manager Console.

Partial View in Asp.Net

And then execute command: PM> Install-Package Microsoft.jQuery.Unobtrusive.Ajax

Partial View in Asp.Net

Create Ajax Helper

• HttpMethod = “GET”, -> specify request method
• UpdateTargetId = “partialview”, – > specify which DIV to be updated with the partial view
• InsertionMode = InsertionMode.Replace – > insertion method. Replace all element inside a DIV

Then we will create an empty DIV that will serve as the container for our partial view.

 

Final Output:

Partial View in Asp.Net

Code Summary
myModel:

_partialview:

HomeController:

Index.html:

 

Thank you for reading..

Enjoy coding!!!

 

 


Post you may like:

[pt_view id=”2384ae03it”]