HTML Helpers are methods that returns HTML strings. These are used in the view. In simple terms, these are C# methods that are used to return HTML. Using HTML helpers you can render a text box, an area, image tag, etc. In MVC we have many built-in HTML helpers and we can create custom helpers too. Using HTML helpers a view can show model properties and can generate HTML as per the types of properties.
Types of HTML Helpers:
- Inline HTML Helper
- Built-in HTML Helper
- Standard HTML helper
- Strongly Typed HTML helper
- Templated HTMl Helper
- Custom HTML Helper
Inline HTML Helpers
These are the type of helpers that are used on a single view and are used on the same page. inline HTML helpers can be created using @helper tag.
You can create your own HTML Helper with the following syntax. @helper HelperName(parameters) { // code } To use the above-created helper we use the following syntax @HelperName(parameters)
Example:
@{ Layout = null;
} <!--created a inline HTMl Helper with a single string type parameter-->
@helper MyInlineHelper(string[] words) { < ol >
<!--Used a foreach loop inside HTML.
similarly we can use any conditional statement
or any logic like
we use in normal C# code.-->
@foreach (string word in words)
{
< li >@word</ li >
}
</ ol >
} <!DOCTYPE html> < html >
< head >
< meta name = "viewport" content = "width=device-width" />
< title >Inline HTML Helper</ title >
</ head >
< body >
< div >
<!--called it inside this
div and to get the output-->
@MyInlineHelper(new string[] {
"Delhi", "Punjab", "Assam", "Bihar" })
</ div >
</ body >
</ html >
|
Output:
Drawback of Inline HTML helpers
- These helpers can only be used with a single view only. You can not use it with multiple views.
Reference: Setup and run code in Visual Studio