ASP.NET MVC @helper Syntax and Html Helper Extension Methods

I need to create my own html helper method. As far as I know, there are two ways:

Which solution is better and why? What are the advantages and disadvantages?

I only read that in MVC 3, when @helper is created globally in a separate .cshtml file, it is not possible to use other built-in html helpers. I don’t know, maybe in MVC 4 it is possible.

Please, help.

+6
source share
3 answers

Which solution is better and why?

It depends.

What are the advantages and disadvantages?

  • HtmlHelper extension profiles:
    • It will work no matter what viewing engine you use.
    • This is a verified entity.
    • It is transferred between applications
  • HtmlHelper Custom Extension Disadvantages:
    • It can become cumbersome to write a lot of HTML logic in C #
  • Pros @helper :
    • Not seen i never use it
  • Against @helper :
    • Not seen i never use it

In fact, the fact is that @helper IMHO is completely useless. If you need the benefits that I mentioned about the HtmlHelper user extension, you can also create the HtmlHelper user extension.

And if you come across some of the flaws that I mentioned about the HtmlHelper user extension, you, well, use a partial view.

I only read that in MVC 3, when @helper is created globally in a separate .cshtml it is not possible to use other built-in html helpers.

It is not right. You could perfectly use other Html helpers. You just need to pass them as parameters:

 @helper FooBar(HtmlHelper html) { feel free to use the html helper here } 

and when consumed from a view:

 @HelperName.FooBar(Html) 
+3
source

One of the benefits of @helper is that since the code is inside the view, you can make changes to it without recompiling your code. This allows you to quickly and easily set up an assistant during development. I personally prefer to keep the markup within sight, if possible, for this very reason.

A related advantage of @helper is that your HTML will be useful for intellisense, while writing HTML in C # code does not get that benefit.

In addition, if you are writing an assistant that is not intended to be reused outside of one view, then @helper makes it easy to fix. The HtmlHelper extension method would be confusing if its purpose is intended to be used (unless you can put it in a class and namespace where only this view will never see the extension method).

+7
source

They may look like Vs Custom Controls.

Use @helper to format the razor style in views. Use extension methods for common solutions, such as overloading label creation, which takes additional parameters.

A detailed explanation can be found with examples here.

+3
source

Source: https://habr.com/ru/post/950060/


All Articles