peter
peter

Reputation: 2103

MVC4 : HtmlHelper - pro & con

What are situations when to definitly use an HtmlHelper?

I'm building a small MVC website for watching tv, each channel is displayed as some sort of enhanced 100px * 100px tile:

On mouseover, e.g.,

Initially, I had defined the markup solely in the view. Now I have created an htmlhelper-method that is being passed one "Channel"-item at a time and returns pretty much the same markup.

I'm not sure if there are objective pro's and con's for any way? I've read that htmlhelpers should only be used for minor operations. I guess this still is a minor operation.

The only pro I figured is that I might need to use the channel tiles on another view as well and with the htmlhelper, I won't have (much) redundant code for this.

Upvotes: 2

Views: 354

Answers (2)

chiccodoro
chiccodoro

Reputation: 14716

Have a look at Display/Editor Templates (e.g. here, here, or here). They are kind of partial views that plug into the @Html.DisplayFor and @Html.EditorFor.

I would argue that:

  • Html Helpers are good if the generated HTML is rather simple and there is much server-side logic involved (e.g. validation based on a server-side model).
  • Partial Views are a good fit if you want to use one part of one page in another page, too. But they are a bit clunky if you want to use them repetitively in many places.
  • This is where display and editor templates fit best.

One more remark: Display and Editor Templates are based on the model type: You define a custom editor and/or display for a certain Type. If you want to use the same pattern of HTML for a variety of models again this might not be a perfect fit. In that case you might want to go for the Html Helpers anyway - they allow to pass in parameters easily. Partial Views don't take parameters. You have to hand them over as a model or in the ViewBag.

Upvotes: 2

Alexandr Mihalciuc
Alexandr Mihalciuc

Reputation: 2577

You are right HtmlHelpers are used when you need to output relatively small amount of html. The reason for it is that html is produced by building strings within c# code, which can be a problem to maintain it as the amount of logic grows inside the helper. I would recommend using partial views for generating html for your case, as it can be reused (using Html.RenderPartial) and it is easy to modify as it an razor view with html intellisense

Upvotes: 0

Related Questions