ASP.NET MVC: Razor @helper vs extension methods to HtmlHelper - which is preferred?

橙三吉。 提交于 2020-01-03 08:29:04

问题


The Razor view engine in ASP.NET MVC supports @helper to define little helper methods. It seems you can do much the same by adding extension methods to HtmlHelper. In what situations is it best to use each?


回答1:


Subjective question, so here's my subjective and biased answer: When the helper code involves amounts of C# code use a custom HtmlHelper and when it's primary markup you could use @helper. But assuming that when you have markup you could use a partial like @Html.Partial("_foo", SomeModel) or an editor/display templates like @Html.EditorFor(x => x.Foo), the @helper doesn't really have any practical use. Personally I've never used @helper by the way, and I've never recommended it's usage to people I've been consulting.




回答2:


Yes, that's true, though the @helpers seem a bit easier to work with if there's a good chunk of markup that's included--Html extensions and more extensive markup don't go that well together, IMO.

On the other hand, @helpers can't be unit tested like Html extensions.



来源:https://stackoverflow.com/questions/6285825/asp-net-mvc-razor-helper-vs-extension-methods-to-htmlhelper-which-is-preferr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!