Partial View in Razor MVC

Partial View allow 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 following peace of code that we would like to make reusable for other views.

We will extract 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 follow the steps:

Step 1

Select above code and cut it.

Step 2

Right click on any view folder to create a new ‘partial view’.

You can use any name for this view page but it is recommended to use (_) underscore sign before the view name that represents something that is reusable. You have also opportunity to select the ‘Model class’ in above dialog to create 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 cut above. You may need to fix-up 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 cut the code, here you go.

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

Hope this helps.


Post a Comment

Popular posts from this blog

Lambda two tables and three tables inner join code samples

Customize User's Profile in ASP.NET Identity System