Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: Use Html.Partial or Html.Action?

I have a site with a navigation bar defined in the layout. The navigation bar is used in several views of the site and has some dynamic content that is generated from a couple of queries in the Database.

I am wondering what is the best practice to render this menu (defined in a partial view).

As far as I know I can do it in two ways, with some advantages and disadvantages for each one:

Using Html.Action: + It's completely independent from the view that is using the layout - It adds an extra request to render a section of the page - I'm adding an Action method that returns a Partial view that is not called from Ajax.

Using Html.Partial: + A simple request to render the entire view - Each view model must contain the information required for the navigation bar

I would really appreciate your insights on this since I have several scenarios like this one on my site and I'm not sure which one is the best.

Thanks!

like image 493
willvv Avatar asked Dec 13 '11 06:12

willvv


1 Answers

I would use Html.Action especially if this menu contains some dynamic data that is fetched from the database. The advantage is that you can completely dissociate this fetching in an entirely separate action from the main one. In addition the output of child actions can be cached by decorating them with the [OutputCache] attribute. By doing this you could reduce the load on your database if the data doesn't change quite often.

It adds an extra request to render a section of the page

You must have misunderstood something about it. There is no additional request from the client. Everything is served in a single request. There is an additional controller instantiation and action execution but not a new HTTP request from the client. It's as if 2 controller actions were executed in the same request and their result aggregated into a single HTML page sent to the client.

like image 180
Darin Dimitrov Avatar answered Oct 19 '22 06:10

Darin Dimitrov