giorgian
giorgian

Reputation: 3825

ASP.NET MVC custom helper objects

I'm going to write a ton of helpers for my app.

For many of them I'd like not to extend HtmlHelper, but to create another helper class instead, for two reasons: 1) to be able to write, say, Link.Home and Icon.Edit instead of Html.HomeLink and Html.IconEdit; 2) to be able to easily tell standard helpers from custom ones and where the latter are defined.

Is this possible? How?

Is this not recommended? why?

thanks

Upvotes: 1

Views: 830

Answers (2)

Robban
Robban

Reputation: 6802

This would be possible by subclassing HtmlHelper and calling the new class Link and Icon for example.

I would not recommend it for the simple reason that Html.HomeLink and Html.IconEdit clearly states what the method does, it outputs Html in the form of a HomeLink and and an Edit Icon.

Upvotes: 0

Anton Gogolev
Anton Gogolev

Reputation: 115751

Well, "helper methods" are just extension methods. If you want to be able to write Link.Home in your views, you'll have to extend ViewPage and add property called Link of type, say, ILink. The ILink interface may itself be empty. Now all your views should inherit from MyViewPage and writing helper methods becomes a simple task:

public static string Home(this ILink link, string text)
{
     // ...
}

Upvotes: 4

Related Questions