Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: When to use custom HTML helper methods vs Html.RenderAction?

It's a little unclear for me on when to use a custom helper method and when to use RenderAction and also when to simply use ViewData instead. Some of their functions overlap slightly.

For example, if I were to create a Category navigation bar, would I create a new helper method and place that in some partial view? I had initially though of doing this, but I read on some blog to use RenderAction instead. I've just been thinking back and forth and could use some help not just with this example, but in general.

Assume the list of categories is coming from some data source.

like image 272
Gabe Avatar asked Feb 10 '10 19:02

Gabe


1 Answers

The general guidelines that I follow are:

HtmlHelper methods:

  1. Used to standardize markup. I use helpers to make sure my form fields, input buttons and image tags use consistent markup.
  2. Used when the resulting markup is minimal. Small bits of text, form field markup, etc. I don't use helpers to render full domain objects.
  3. Operate on a small number of discrete arguments. If I need to iterate over a collection and display something, that's a partial. If I need to take a large amount of input, that's a partial too.
  4. Do not contain any business logic, just presentation logic. The arguments are usually objects in the solution domain, not the business/problem domain.
  5. Are usually very general in scope and apply to large portions of the application.

Render partial:

  1. Used when I want to decompose a large view into smaller pieces. The model should be a subset of the model of the "main" view.
  2. Partial views are often used only by certain controllers or areas.

Render action:

  1. Used when I want to create small chunks of functionality that can be composed in various ways.
  2. Most often used to generate content that applies to many controllers or areas, such as navigation controls.

ViewData:

I'll use ViewData to track global data that applies to all views, such as the current user. If I need a consistent way of displaying this data I usually create a partial for it and then do RenderPartial() in a master page.

like image 171
Seth Petry-Johnson Avatar answered Nov 08 '22 14:11

Seth Petry-Johnson