ASP.NET MVC Custom HTML Helpers (C#)





5.00/5 (1 vote)
Create custom HTML Helpers to make it easier to generate view content.
Create custom HTML Helpers to make it easier to generate view content. You can create custom helpers in three ways:
- with Static Methods
- with Extension Methods
- with @helper in the razor view
1. Static Methods:
CustomHelper.cs:
using System;
using System.Web.Mvc;
namespace HelperApplication.Helpers
{
public static class CustomHelpers
{
public static string ImageTag(string src, string alt = "Image", int width = 50, int height = 50)
{
return String.Format("<img src='{0}' alt=’{1}’ width=’{2}’ height=’{3}’/>", src, alt, width, height);
}
}
}
src
- image source (path)alt
- alternative text if image could not be loaded, and it is assigned a default value "Image". When no values is passed to this parameter it will take the default value "Image".width
andheight
- width and height of the image these parameters are also assigned a default value 50
Using the ImageTag
HTML helper method..
Index.cshtml:
@using HelperApplication.Helpers.CustomHelper
<div>
<span>ImageTag with default values for alt, width, height</span>
@ImageTag("imagePath")
</div>
<div>
<span>ImageTag with width=100 and height=100</span>
@ImageTag("imagePath","Image With alt",100,100)
</div>