Why do we use HTML helper in ASP.NET MVC?

2020-03-01 05:37发布

问题:

Are there any good thing, best practice or profit we have after using the HTML helper in an ASP.NET MVC project?

When I am trying to use them I found that I lose the speed I have with HTML and many difficulties I have whenever I use an HTML helper.

Other [non-techie] persons can't understand what I write using Helper if I want to show them or they want to do something they need to spent more time on, even if they have working knowledge of HTML.

If I use an HTML helper I lose the speed. When I use HTML I just type and of course I am not aware of it. But using helper, it is hard to understand.

What thing do we get when I use HTML helper? I think it is nothing I get because I lose the speeed. Others can't understand what I do using helper and can't customize the code if they want.

Why do we use HTML helpers?

回答1:

You use HTML helpers to encapsulate some small HTML fragments which are repeated all over your pages. And to avoid writing those HTML snippets all over again you use helpers.

They are very useful, especially when dealing with things like URLs because instead of hardcoding your links helpers take advantage of routing the definition on your server and by simply changing those routes the whole site URLs' change without ever touching any single HTML page.

Another scenario where HTML helpers are useful is for generating form input fields. In this case they automatically could handle values when posting back and show associated validation messages. Can you imagine the spaghetti code you would have to write in your views if there weren't HTML helpers?



回答2:

The biggest advantage I find is with the editor and display templates.

If your editor for a field is more than just a simple input box, you can put that into a template and replace the several tags with a call to

<%:Html.EditorFor(m=>m.Property)%>

This means that your page is a lot easier to edit as you aren't wading through a lot of fluff HTML to find what you want.