ASP.NET MVC: When to use HTML helpers in views - Tidying up the code! - asp.net-mvc

I am trying to refactor my views a bit and up til now i have been using the built HTML helpers but i thought i would create my own - they're extension methods right?
I wonder if anyone can confirm or give advise when an HTML is needed? I think i once saw a document that said if you use 1 IF statement in your views encapsulate it into a html helper - would anyone agree with that?
With regards to creating html helpers, would it be better to create my own class rather than add extension methods to the HTML class that ships with MVC? Any body have ideas on this?
Or possible i shouldn't bother with HTML helpers and just use the built in ones and continue to use my IF statements within views.
Thanks in advance

Use HTML helpers when you want to encapsulate the output of a piece of HTML markup that can take varying values.
I'd recommend creating them as extension methods to HtmlHelper rather than creating your own class, as your own class won't be available inside of the default ViewPage without either instantiating a new instance inside of the View or subclassing ViewPage and using this in the View (or passing in on the model, but that's just wrong!).

HTML Helpers are extension methods. I can confirm as well that I too use the 'if' rule when it comes to views. Any view logic coded should, IMO, be in a helper.
You can use helper to render custom markup, or control which markup(ie existing view) is displayed.
Not too sure about the ease of this, but it does lend itself to more unit testing (please comment on this aspect if someone has more info).
With regards to creating html helpers, would it be better to create my own class rather than add extension methods to the HTML class that ships with MVC? Any body have ideas on this?
If I understand correctly, in this respect my suggestion would to separate your helpers into their own classes. The reasoning behind this for me would be that you easily know when looking at your views what are standard helpers vs the ones you've created. I think this will improve maintainability.
i shouldn't bother with HTML helpers and just use the built in ones and continue to use my IF statements within views.
I'd say No! (or it depends). One of the benefits of using a helper would be to reuse the same view logic in multiple views as opposed to re-coding the same if statements. This means your code is more DRY, which is always better. In the event you need to debug some weirdness error, you only need to look in one place, the newly created helper.

Related

Is it a good practice to write helper functions in controller itself

I am new to Microsoft ASP.NET MVC framework. I am working on MVC project where I have a controller. It has various ActionResult methods. Also, it needs several helper functions. Can I write them in controller itself? Please guide me.
No, it's not best practice.As helper function needs to be define/implemented in static class. So it is better to to have standalone seprate helper class.
The answer is: it depends. First of all it is not clear what do you mean with helper functions.
if you are talking about ASP.NET MVC HTML Helpers, it is better to move them to separate class. Tutorial how to create and use them.
if you are talking about general helper functions that evaluate something, of course you may leave them in controller, move to the base controller or move to separate class or library (depeneds on context). You may check implementation of standard System.Web.Mvc.Controller, there are a lot of methods and properties in it.
I think there's no specific rule regarding this.
IF
you're going to reuse the helper function, abstract/separate it to another class.
ELSE
put it in the same class for better code cohesion and readability.

ASP.NET MVC3 first time questions

I am building my first mvc3 app. A few questions I have are:
1) the razor view engine lets me embed code into the views. Is this not what we were once trying to get away? ie keep code out of the aspx.
2) Do models need to implement an interface?
3) Do models need to have methods? Or just properties?
Thanks
Pretty vague question, but I'll give you my 5c worth:
True, but the code we put in the Razor views are usually only to generate Html-controls.. the helper methods in MVC3 utilizes data attributes from your Viewmodels and generates validation etc.
When that is said, it's completely optional how much code you wish to put in your views.
No.
Viewmodels should be as stupid (POCO) as possible, and business logic method should be put on your domain models, as the good DDD developer you are ;)
The code that you put in the view is supposed to be rendering code only. Simple for loops for repetition, calls to EditorFor or DisplayFor or stuff like using (Html.BeginForm()). The main business logic should never be placed in the View layer.
No.
No, just properties. You can add really simple helper methods, but the important stuff is the properties, so even the helper stuff should be implemented as readonly properties.
Actually, the first part is true for the aspx engine and WebForms as well. And Php, and classic ASP, and...
1) It may seem a bit like that, but really it depends what the code is. IMHO You should really avoid any logic or code in the view, other than that directly related to rendering the view. For this code though, Razor gives a lovely clean way of coding in the view.
2) No - any class can be a model.
3) There is nothing to stop you putting methods on the model - but really they should be very simple data tranfer objects - they just "carry" data around. So more often than not, stick to properties.
1) the razor view engine lets me embed code into the views. Is this not what we were once trying to get away? ie keep code out of the aspx.
No, we were once trying to get the logic out of the view. This gives a bit more control over the view, but should not be used as a method of implementing logic.
2) Do models need to implement an interface?
Nope.
3) Do models need to have methods? Or just properties?
Models are just classes. They define the structure of your class.

Is It Okay to use helpers in views?

Simple question about best-practice. I'm using Kohana... is it okay to use helpers in views? For example, to use URL::site(). I could pass it from controller, you know. I assume it's okay, because there are helpers like HTML that is meant to be used in views, right?
The way you're currently doing it is ok, altough the whole practice of having any logics in views is questionable, but it's how Kohana is currently recommending.
When you get to use ViewModel pattern (with Kostache?), you'll separate all logics from templates. Until then, it's ok to use methods that don't do anything that should be done in the controller / model (echo, conditions and loops are "considered allowed").

What are the differences between editor templates and partial views?

I am simply looking for how these two are different and what are their pros and cons?
It seems you can do all with partial views that you can do with templates.
If you are referring to EditorTemplates (rather than inline timeplates), then there are some big differences. First, partial views require you to specify your view when you use them, while templates work on the type of the data object.
Second, because templates work on data types, then when you make a change to the template, it changes it everywhere that type is used, not just where the partial view is used (this can be a disadvantage as well in some cases).
Third, templates are passed additional information that partial views are not, in particular you recieve Model Metadata, such as that created by attributes.
if you mean "inline helpers", they are simply an easier way of building the equivalent of HtmlHelper extension methods - but they are only for use in the specific view. partial views, on the other hand, can have more logic behind them (via their controller) without violating MVC and they can be easily reused from multiple views

When should I use HtmlHelper Extension Methods?

I am increasingly finding situations where my ASP.NET MVC view requires some logic to perform layout. These routines have no place being in either my model or my controller. I have 3 options:
Write lots of <% %> inline in the view.
Write less <% %> in a number of partial views.
Write an HtmlHelper Extension method.
It is the last option that confuses me. Is it OK to do this if the logic is specific to only that one view? The extension would be 'visible' to the Html object of every other view, and it will never be needed.
Any suggestions?
I personally prefer option 3 ("Write an HtmlHelper Extension method") because those bodies of code lend themselves to be easily unit testable.
I really do wish extension methods could be placed on internal or nested classes because you are right, you will begin to pollute your namespaces with tons of extension methods which are only used in one View.
I'd recommend sequestering these HtmlHelper extension methods in static classes in a custom namespace per View that you manually reference in the View so as to limit the number of extension methods available throughout your project.
I would, generally, limit both partial views and extension methods to reusable components, but am not pedantic about it. If you feel that either one improves the readability of your code, then go ahead and use them. You might want to consider a separate namespace/helper class for helper methods that are only used by one set of views -- sort of like segregating your partials per controller.
You might also want to consider using more whitespace (even though it's the silent killer) to improve readability. I've implemented output compression in my base controller to limit the impact of whitespace on download time.
Is it OK to do this if the logic
is specific to only that one view?
Yes. Read on...
The
extension would be 'visible' to the
Html object of every other view, and
it will never be needed.
No true. It depende how you register the extension method for the view. This is only the case if you add the namespace to the web.config namespaces section.
If you want to use the extension method on a single view just import its namespace to the single view:
<%# Import Namespace="NamespaceOf.Your.ExtensionMethods.ForThisViewOnly"%>

Resources