# ASP.NET Core: HTML Helper

### **1\. What is an HTML Helper?**

An HTML Helper is a method used within a Razor View (`.cshtml`) to render HTML content. It acts as a wrapper that generates raw HTML strings, saving developers from manually typing standard HTML tags.

Technically, they are extension methods of the `IHtmlHelper` interface, accessed via the `@Html` property in a view.

---

### **2\. The Three Types of HTML Helpers**

There are three main categories of helpers you will use.

#### **A. Standard Helpers**

These are loosely typed. You pass the name of the form field as a string.

* **Risk:** No compile-time checking. If you misspell the string, it breaks at runtime.
    
* **Example:** `@Html.TextBox("FirstName")`
    

#### **B. Strongly Typed Helpers (Recommended)**

These bind directly to your Model properties using lambda expressions.

* **Benefit:** Compile-time safety. If you change a model property name, your code will fail to compile (alerting you immediately) rather than breaking silently.
    
* **Naming Convention:** Always end in suffix `...For`.
    
* **Example:** `@Html.TextBoxFor(m => m.FirstName)`
    

#### **C. Templated Helpers**

These are "smart" helpers that look at the data type and Data Annotations of your model property to decide what HTML to render.

* **Example:** `@Html.EditorFor(m => m.BirthDate)` might render a date picker automatically if the property is a `DateTime`.
    

---

### **3\. Common HTML Helpers (Categorized)**

#### **I. Form Generation**

The `BeginForm` helper creates the `<form>` opening tag. It is almost always used within a `using` block so that the closing `</form>` tag is generated automatically at the end of the block.

```csharp
@using (Html.BeginForm("Submit", "Account", FormMethod.Post, new { @class = "login-form" }))
{
    <input type="submit" value="Save" />
}
```

**Renders:** `<form action="/Account/Submit" method="post" class="login-form"> ... </form>`

#### **II. Input Controls**

| **Helper Name** | **Usage** | **HTML Output** |
| --- | --- | --- |
| **TextBoxFor** | `@Html.TextBoxFor(m =>` [`m.Name`](http://m.Name)`)` | `<input type="text" name="Name" ... />` |
| **TextAreaFor** | `@Html.TextAreaFor(m =>` [`m.Bio`](http://m.Bio)`)` | `<textarea name="Bio">...</textarea>` |
| **PasswordFor** | `@Html.PasswordFor(m => m.Password)` | `<input type="password" ... />` |
| **HiddenFor** | `@Html.HiddenFor(m =>` [`m.Id`](http://m.Id)`)` | `<input type="hidden" ... />` |
| **CheckBoxFor** | `@Html.CheckBoxFor(m => m.IsActive)` | `<input type="checkbox" ... />` (+ hidden input) |
| **RadioButtonFor** | `@Html.RadioButtonFor(m => m.Gender, "M")` | `<input type="radio" value="M" ... />` |

> **Note on CheckBoxFor:** It renders **two** inputs (one checkbox, one hidden). This is a trick to ensure `false` is sent to the server if the checkbox is unchecked (since unchecked boxes don't send values in standard HTML).

#### **III. Dropdowns & Lists**

This is often the trickiest part for beginners. It requires a list of `SelectListItem`.

```csharp
// In Controller/Model preparation
var countryList = new List<SelectListItem>
{
    new SelectListItem { Text = "USA", Value = "US" },
    new SelectListItem { Text = "Canada", Value = "CA" }
};

// In View
@Html.DropDownListFor(m => m.CountryCode, countryList, "Select a Country", new { @class = "form-select" })
```

**Renders:** `<select name="CountryCode"> <option value="">Select a Country</option> ... </select>`

#### **IV. Labels & Display**

* **LabelFor:** Generates a `<label>` element. It reads the `[DisplayName]` attribute from your model if it exists.
    
    ```csharp
    @Html.LabelFor(m => m.Email) 
    // Renders: <label for="Email">Email Address</label>
    ```
    
* **DisplayFor:** Renders the text value of the property (read-only). It respects formatting strings (e.g., currency).
    
    ```csharp
    @Html.DisplayFor(m => m.Price) 
    // Renders: $99.00 (Plain text, no input tag)
    ```
    

#### **V. Links**

Used to generate `<a>` tags pointing to controller actions.

```csharp
@Html.ActionLink("Edit Profile", "Edit", "User", new { id = 5 }, null)
```

Parameters: Link Text, Action Name, Controller Name, Route Values (ID), HTML Attributes.

Renders: &lt;a href="/User/Edit/5"&gt;Edit Profile&lt;/a&gt;

#### **VI. Validation**

Used to display error messages generated by Model Validation (Data Annotations).

* **ValidationMessageFor:** Shows error for a single field.
    
    ```csharp
    @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" })
    ```
    
* **ValidationSummary:** Shows a list of all errors in the form (or just model-level errors).
    
    ```csharp
    @Html.ValidationSummary(true, "Please fix the errors:", new { @class = "alert alert-danger" })
    ```
    

---

### **4\. Handling HTML Attributes**

Since HTML Helpers are C# methods, you cannot just type `class="btn"` inside them. You must pass an **Anonymous Object**.

The @ Escape Character:

Because class is a reserved keyword in C# (used to define a class), you must prefix it with @ when using it as a property name.

```csharp
@Html.TextBoxFor(m => m.Name, new { @class = "form-control", @readonly = "readonly", style = "color:red" })
```

---

### **5\. Security:** `Html.Raw` vs Standard Helpers

By default, all HTML Helpers (like `TextBoxFor`) automatically **encode** the output.

* If your data contains `<script>alert('hack')</script>`, the helper converts it to `&lt;script&gt;...` so it displays as safe text rather than running the code.
    

Using Html.Raw:

If you strictly intend to render HTML stored in your database (e.g., a blog post with bold tags), you must use Html.Raw.

```csharp
@Html.Raw(Model.BlogPostContent)
```

> **Warning:** Never use `Html.Raw` on user input without sanitizing it first, or you create XSS (Cross-Site Scripting) vulnerabilities.

---

### **6\. Creating Custom HTML Helpers**

If you have a snippet of HTML you repeat often (like a specific button style), you can create your own helper extension method.

**Step 1: Create a Static Class**

```csharp
namespace MyApp.Helpers
{
    public static class MyHtmlHelpers
    {
        public static IHtmlContent SubmitButton(this IHtmlHelper htmlHelper, string text)
        {
            string str = $"<input type='submit' value='{text}' class='btn btn-primary' />";
            return new HtmlString(str);
        }
    }
}
```

Step 2: Use in View

Import the namespace and call it.

```csharp
@using MyApp.Helpers

@Html.SubmitButton("Save Changes")
```

---

### **Summary Checklist**

* **Prefix:** Always accessed via `@Html`.
    
* **Type:** Prefer **Strongly Typed** (`...For`) versions for safety.
    
* **Styling:** Use `new { @class = "..." }` to add CSS.
    
* **Lists:** `DropDownList` requires a list of `SelectListItem`.
    
* **Safety:** Standard helpers prevent XSS attacks; `Html.Raw` does not.
