Friday, 12 April 2019

Call main view inside the view like partial view in MVC



In MVC, normally users create a partial view and reuse the partial view in any of the main view. The developer generally creates a partial view using point and click option.




  
And when we generate this partial view, there is nothing in the view which identifies that this is a partial view like below



I was new in MVC pattern and worked on asp.net web forms, therefore I asked my developer fellows why we mark to check that it is partial view and use this view as a partial view, why we can’t reuse the normal view as a partial view, I got no answer. Therefore I tried something which I wanted to do 😊. My scenario is that I have an Account model which is the parent table, Contact and Opportunity are the children of Account. I wanted to show the list views of Contact and Opportunity in the Account Detail view, already made a complete set of views of Contact & Opportunity which are behaving independently. Let’s take the example of Contact, Contact list view is driven from the stored procedure and looks like below



 To call this contact list view inside the detail view of account, use the below code in Account Detail view



Above snapshot shows the complete code which is rendering the list views of contact & opportunity as a partial view inside the detail view of Account view. Firstly I called the same stored procedures and pass the account id which actually filters out the contacts and opportunity based on the account id then pass the generic list of contact & opportunity to the list view of contact & opportunity. This code makes our life easy because we only changing the code only at this level, no need to update the list views of contact & opportunity. The actual detail view of the Account now looks like below screenshot





We have learned how we reuse the main views inside any views, no need to create separate partial views, we can create partial views based on requirements

No comments:

Post a Comment