- Creating Extension Method on Html Helper Class
- Creating Static Methods
ASP.NET MVC Custom Html Helper using Extension Method
If we want a custom Html Helper to be used just like standard Html
helper, then available approach is to create an extension method on Html
Helper class. Custom Html Helpers we create using Extension methods
will be available to Html property of View.
For the purpose of implementation, we will create a custom Html Helper
i.e. “CustomImage” using extension method approach as follows:
namespace CustomHelpers
{
public static class ImageHelper
{
public static MvcHtmlString CustomImage(this HtmlHelper htmlHelper,
string src, string alt, int width, int height)
{
var imageTag = new TagBuilder(“image”);
imageTag.MergeAttribute(“src”, src);
imageTag.MergeAttribute(“alt”, alt);
imageTag.MergeAttribute(“width”, width.ToString());
imageTag.MergeAttribute(“height”, height.ToString());
return MvcHtmlString.Create(imageTag.ToString(TagRenderMode.SelfClosing));
}
}
}
In order to make this extension method available in all Views, we will add CustomHelper namespace to namespace section of View’s web.config as follows:
<add namespace=”CustomHelpers” />
Now we can use CustomImage helper in Views. We will pass image source, alternate text, image width and height to our View as follows:
@Html.CustomImage(“../Images/Ahmad.jpg”, “Mohammad Ahmad”, 150, 200)
Using the same approach, we can create any Custom Html Helper to simplify the task of writing lots of Html code repeatedly.ASP.NET MVC Custom Html Helper using Static Methods
Second available approach for creating Custom Html Helper is by using Static Methods. It’s also as simple as that of above mentioned Extension Method approach. We will create a static method for TextBox that renders an HTML TextBox as string.namespace CustomHelpers
{
public static class CustomTextBox
{
public static string TextBox(string name, string value)
{
return String.Format(“<input id='{0}’ name='{0}’ value='{1}’ type=”text” />”, name, value);
}
}
}
Verify the namespace is added to Web.Config namespace section as we did before for Extension Method approach.
<add namespace=”CustomHelpers” />
Now, we can simply use the CustomTextBox in our View as follows:
@CustomTextBox.TextBox(“strStudentName”, “Mohammad Ahmad”)
We can use the Static Method approach to generate more HTML rich Custom Helper in ASP.NET MVC.
No comments:
Post a Comment