Custom html helpers can be created by extension methods. Extension method can be crated by static methods in static class. In my example I am going to create two custom html helpers for html submit button and for image.In built-in or standard html helpers there are no helpers for submit and for image.
Step: First we add class in project folder and write following code.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CustomHTMLHelpers { public static class CustomHtmlHelpers { public static MvcHtmlString Submitbtn(this HtmlHelper mvc, string name, string value) { string str = ("<input type='submit' value=" + value + " name=" + name+" />;"); return new MvcHtmlString(str); } public static MvcHtmlString Img(this HtmlHelper mvc, string src, string alt) { var ctrl = new TagBuilder("img"); ctrl.MergeAttribute("src", src); ctrl.MergeAttribute("alt", alt); ctrl.MergeAttribute("width", "200px"); ctrl.MergeAttribute("height", "200px"); return MvcHtmlString.Create(ctrl.ToString(TagRenderMode.SelfClosing)); } } }
Step 2: Create New Controller and create and action into that controller.
public ActionResult Index() { return View(); }
step3: Add View and write following code.
@{ Layout = null; }
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <div> @Html.Submitbtn("aa","bb") @Html.Img("../images/Desert.jpg","This is Image"); </div> </body> </html>
Thank you for the effort, keep up the great work
Great work.