Thursday, October 8, 2015

Partial View

Intorduction

Hope you all aware concept of UserControl in asp.net which is use for making common things in one control and use everywhere in web application.

Similarly in MVC we have Partial View which renders the view content.Meaning it helps you to reduce your code and also avoid duplication.

For example if you have Address Control which includes address related controls and you have to put address in many place in your web application. So here you can make Partial view which reduce your time and duplication.

Create Partial View

Below are few steps to create Partial view and How to use of it :

Step 1 : To create partial view go to your solution and go to view folder and right click on View folder.and follow below image.

Add New Partial View

Step 2 :  Click on view and it will open below window, Now in that you need to tick "Create Partial view" and you have now same view as normal view but it will created as a partial view.


Now if you want to reuse partial view then its good habit to put in "Shared" folder under Views folder so you can view in whole application

Step 3 :  To call and render partial view you can use below two methods.Below are two method to call partial view


  1.   
  2.     @Html.Partial("PartialView")  
 
  •  
  •   
  •     @{  
  •         Html.RenderPartial("PartialView");  
  •     }  

  • @Html.Partial - This method renders the view as an HTML-encoded string. So using this method we can store result in string.

    @Html.RenderPartial - This method is written directly into the HTTP response, it means that this method used the same TextWriter object as used by the current view. This method returns nothing.

    Step 4 - Render Partial view from controller file using below approach:

    1. public ActionResult PartialView()  
    2. {  
    3.     return PartialView();  
    4. }  
      

    Using this way you can create Partial view and render and call your view.You can also pass the model to the partial view for strongly binding same as we pass in normal view.







    No comments:

    Post a Comment