Updated on Kisan Patel
The HTML helper class provide a lots of utilities to make easier to work with model data to generate HTML and also generate URLs and also you can create custom HTML element using HTML helper classes.
Lets generate custom extension methods for the HTML helper class to generate HTML we need.
First add the ParagraphExtensions
class as shown in below screenshot.
Now, add below line of code into the ParagraphExtensions.cs
class.
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MvcElementDemo { public static class ParagraphExtensions { public static MvcHtmlString Paragraph(this HtmlHelper html, string content) { return MvcHtmlString.Create(string.Format("<p>{0}</p>", content)); } } }
In above code. you can see we will add extensions method called Paragraph that extend the HtmlHelper
and also pass the content
as string variable. Here we will use Create
method of MvcHtmlString
class that encode the Html string.
Now Create HomeController
and add Index
action method then also add Index
view.
Now, Open Index.cshtml then add below line of code.
@using MvcElementDemo @{ ViewBag.Title = "Index"; } <h2>Index</h2> @Html.Paragraph("test paragraph")
Here you can see how we can use Paragraph
extension methods in Index.cshtml
view. When you run the application then you will see output as shown in below.