App
Code - Function and Similar Helpers
Reuse Code with @functions { }
Any kind of code to do some work such as figure out a string or calculate something should be placed in a function. In Razor these are put inside a functions block.
⬇️ Result | Source ➡️
- Random number: 77
- Random number: 40
This example passes a parameter into the function.
⬇️ Result | Source ➡️
- iJungleboy is cool 😎
- Douglas Adams is cool 😎
This example using a string
and a bool
parameter.
Note also that any HTML we return is not handled as expected. So we show an example with/without @Html.Raw
⬇️ Result | Source ➡️
- iJungleboy is <em>ok 😉</em>
- Douglas Adams is <strong>cool 😎</strong>
- iJungleboy is ok 😉
- Douglas Adams is cool 😎
This example is similar, but returns a dynamic
HTML which is marked to be shown as HTML.
Note this example correctly shows bold and emphasis.
⬇️ Result | Source ➡️
- iJungleboy is ok 😉
- Douglas Adams is cool 😎
The above examples show how you can get things done, but of course writing HTML directly into a string doesn't look ideal. We can do better, check the Other-Tutorials Tab
- Code - Function and Similar Helpers
Normal C# functions are the basic block for reusing code.
- RazorBlade Basic Html5
Tag
API Introduction v3.0The basics of creating html directly from code
HTML-functions = Code-Snippet with Template Delegates
If you just need a quick simple snippet, Template Delegates are the way to go. They are very limited so only ideal for simple stuff.
Template Delegates allow you to use inline HTML in your function. To make this possible, a bit of magic happens automatically, so a limitations is that you cannot use named parameters. You only get one parameter called item
.
Basic Example: string
generating Html
This example using a string
parameter. This is why the the first parameter in Func<...
is a string.
item
is the thing passed into the function.⬇️ Result | Source ➡️
- this is text, it doesn't have tags
- this string has html tags
- this is just a bold line
If you have multiple values, you often want to merge in into one object like this:
⬇️ Result | Source ➡️
- this is text, it doesn't have tags 🌟
- this string has html tags