
Webpages Helpers in ASP
Absolutely! Here's a simple guide to Helpers in ASP.NET Web Pages (WebMatrix) — which let you create reusable functions to keep your code clean and modular.
ASP.NET Web Pages Helpers
What Are Helpers?
Helpers are custom functions or reusable code snippets you define to simplify common tasks like formatting data, generating HTML, or encapsulating business logic.
You create helpers as either:
Inline helper functions inside your
.cshtml
page, orReusable helper files you include across pages.
1. Creating a Simple Inline Helper Function
Inside a .cshtml
file, define a helper with the @helper
keyword:
@helper FormatDate(DateTime date) { <span>@date.ToString("MMMM dd, yyyy")</span>}<p>Today's date: @FormatDate(DateTime.Now)</p>
2. Creating a Helper That Returns a String
@helper MakeLink(string url, string text) { <a href="@url">@text</a>}@MakeLink("https://openai.com", "OpenAI Website")
3. Using Helper Functions in Multiple Pages
Option A: Put helper functions in a separate .cshtml
file (e.g., _Helpers.cshtml
)
@helper FormatCurrency(decimal amount) { <span>$@amount.ToString("F2")</span>}
Option B: Include this helper file where needed:
@{ Layout = null; var helpers = RenderPage("_Helpers.cshtml"); }@FormatCurrency(123.45m)
Or simply place _Helpers.cshtml
at the root and call helpers from there.
4. Helper for HTML Encoding
Create helpers to output safe HTML:
@helper Encode(string text) { @Html.Encode(text)}<p>@Encode("<script>alert('xss')</script>")</p>
5. Helper for Conditional HTML
@helper ShowIf(bool condition, HelperResult content) { if(condition) { @content }}@ShowIf(true, @<p>This will show</p>)@ShowIf(false, @<p>This will NOT show</p>)
Summary
Task | How To Do It |
---|---|
Define inline helper | @helper HelperName(params) { ... } |
Call a helper | @HelperName(arguments) |
Share helpers across pages | Put helpers in _Helpers.cshtml and include via RenderPage() |
Return HTML or text | Use <span>...</span> or @Html.Encode() |
If you want examples of advanced helpers, like helpers with multiple parameters, or helpers returning complex HTML (tables, forms), just ask!