Partial View in MVC

Partial View allows us to put HTML and C# code into a file that we can reuse across multiple other views. This is very useful when you work on a large application.


Assume we have the following peice of code that we would like to make reusable for other views.



We will extract the above marked code and paste it in a new "partial view" and then we'll just call that "partial view" from this foreach loop. Please use the following.


Step 1


Select the above code and copy it to the clipboard.


Step 2


Right-click on any view folder to create a new "partial view".



You can use any name for this view page but the underscore sign (_) is recommended to be used before the view name that represents something that is reusable. You also have the opportunity to select the "Model class" in the above dialog to create a strongly typed view. And remember to check the checkbox "Create as a partial view".


Step 3


Now, in the "partial view" page paste all the code you copied above. You may need to fix some errors here like @item.Name will become @Model.Name. Here is the complete code:



Step 4


One more thing, you need to place a reference at the location from where we copied the code, here you go:



Remember to pass the "partial view" name and model name. Now, run the application, your application will work the same because we just set up a new structure in the application.


Hope this helps.


Similar Articles