简体   繁体   中英

What is the difference between a function and a helper in Razor?

From the tutorials I've read, functions always contain C# code. Is this always the case or can we have Razor syntax in functions? On the other side, can we have C# code in helpers?

Use functions for processing and helpers for display purposes.

functions are used for defining C# code , and only C# code, that pertains to your page. A location where you could perform some (preferably small) data operations, etc. Granted this should really be in a controller or service layer and then passed to your model.

Meanwhile helpers are for actual display. A way to write HTML as HTML without having to use plain strings, TagBuilders or other messy C# tactics to spit out HTML.

Yes they are "reusable" as others have said. So would a static C# method in your page... (rhetorical) why not just do that?

The point is to be able to create/edit HTML in a more natural HTML environment.

And yes you can have C# code inside your helpers using the regular old @ razor syntax. But again should be limited to display purposes by convention. IE: Looping through a list to create elements, etc.

The difference between razor helpers and functions is as follows:

A helper is a reusable piece of code used for rendering HTML, the return type is always HelperResult .

A function is a static utility that can be called anywhere from within your razor file and can have different return types.

Although this is for the WebMatrix this article here should clear it up for you:

http://www.mikesdotnetting.com/Article/173/The-Difference-Between-@Helpers-and-@Functions-In-WebMatrix

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM