Loading

ASP.NET MVC

What is Custom HTML Helpers in ASP.NET MVC?. The Complete ASP.NET MVC Developer Course 2023 [Videos].

In this Video, I am going to discuss how to create Custom HTML Helpers in ASP.NET MVC application. Please read our previous Video, where we discussed how to Customizing Template Helpers in ASP.NET MVC application. As part of this Video, we are going to discuss the following two things

  1. How we can display Images in an ASP.NET MVC application?
  2. How to create Custom HTML Helpers in MVC to display images?

As we already discussed the HTML helper is a method that returns an HTML string. Then this HTML string is rendered in a view. ASP.NET MVC provides many built-in HTML helper methods that we can directly use in a view. The MVC framework also provides the facility to create Custom HTML Helpers in ASP.NET MVC application. Once you create your custom HTML helper method then you can reuse it many times. 

Lets understand Custom HTML Helpers in MVC with an example.

In this demo, we are going to display the employee details along with the Employee photo as shown in the below image. 

Creating Custom HTML Helpers in ASP.NET MVC application

Creating an empty ASP.NET MVC application

First, create an empty ASP.NET MVC application with the name CustomHTMLHelper. Then create one model class with the name Employee within the Models Folder and then copy and paste the following code in it.

namespace CustomHTMLHelper.Models
{
public partial class Employee
{
public int Id { get; set; }
public string FullName { get; set; }
public string Gender { get; set; }
public string EmailAddress { get; set; }
public string PersonalWebSite { get; set; }
public string Photo { get; set; }
public string AlternateText { get; set; }
}
}

Then add a folder with the Name Photos to the project.

To do this, Right-click on the Project and select Add Folder and then rename the folder as “Photos“. Then download and add the following image within the Photos Folder. Rename the image name as MyPhoto.png.Custom HTML Helpers in ASP.NET MVC

Creating Controller:  

Now add a controller with the name EmployeeController within the Controllers folder and then copy and paste the below codes.

namespace CustomHTMLHelper.Controllers
{
public class EmployeeController : Controller
{
public ActionResult Details()
{
//Here we are hardcoded the Employee Details
//In Realtime you will get the data from any data source
Employee employee = new Employee()
{
Id = 1,
FullName = "Pranaya Rout",
Gender = "Male",
EmailAddress = "info@dotnettutorials.com",
PersonalWebSite = "https://dotnettutorials.net/",
Photo = "~/Photos/MyPhoto.png",
AlternateText = "Pranaya Rout Photo not available"
};
return View(employee);
}
}
}
Adding View:

Add the Details view and then copy and paste the following codes in it.

@model CustomHTMLHelper.Models.Employee
@{
ViewBag.Title = "Details";
}
<div>
<h4>Employee Details</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.FullName)
</dt>
<dd>
@Html.DisplayFor(model => model.FullName)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Gender)
</dt>
<dd>
@Html.DisplayFor(model => model.Gender)
</dd>
<dt>
@Html.DisplayNameFor(model => model.EmailAddress)
</dt>
<dd>
@Html.DisplayFor(model => model.EmailAddress)
</dd>
<dt>
@Html.DisplayNameFor(model => model.PersonalWebSite)
</dt>
<dd>
@Html.DisplayFor(model => model.PersonalWebSite)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Photo)
</dt>
<dd>
@Html.DisplayFor(model => model.Photo)
</dd>
<dt>
@Html.DisplayNameFor(model => model.AlternateText)
</dt>
<dd>
@Html.DisplayFor(model => model.AlternateText)
</dd>
</dl>
</div>

Now Run the application and navigates to the URL http://localhost:61629/Employee/Details It will produce the following output.

How we can display Images in an ASP.NET MVC application

Notice instead of rendering the photo, the PhotoPath and AlternateText property values are displayed.

How to display an image in ASP.NET MVC Application?
<dt>
@Html.DisplayNameFor(model => model.Photo)
</dt>
<dd>
@Html.DisplayFor(model => model.Photo)
</dd>
<dt>
@Html.DisplayNameFor(model => model.AlternateText)
</dt>
<dd>
@Html.DisplayFor(model => model.AlternateText)
</dd>
Replace the above code with the following code.
<dt>
@Html.DisplayNameFor(model => model.Photo)
</dt>
<dd>
<img src="@Url.Content(@Model.Photo)" alt="@Model.AlternateText" />
</dd>

Notice that, now we are using the Url.Content() HTML helper method. This method resolves a URL for a resource when we pass it the relative path. Now, run the application, and notice that the image is displayed as expected as shown in the below image.

Custom HTML Helpers in MVC application

We use the below code to render Image in ASP.NET MVC application. We are building the image tag, by passing the values for “src” and “alt” attributes.

<img src=”@Url.Content(@Model.Photo)” alt=”@Model.AlternateText” />

Though the above code is not very complex, it still makes sense to move this logic into its own helper method. We dont want any complicated logic in our views. Views should be as simple as possible. Dont you think, it would be very nice, if we can render the image, using Image() HTML helper method as shown below.

@Html.Image(Model.Photo, Model.AlternateText)

But, ASP.NET MVC does not provide any built-in Image() HTML helper. So, lets build our own custom image HTML helper method. Lets take a step back and understand HTML helper methods. The HTML helper method simply returns a string. To generate a textbox, we use the following code in our view.

@Html.TextBox(“TextBox Name”)

So, here TextBox() is an extension method defined in HtmlHelper class. In the above code, Html is the property of the View, which returns an instance of the HtmlHelper class.

Creating Image() extension method, to HtmlHelper class. 

Right-click on the project and add the “CustomHelpers” folder.  Then Right-click on the “CustomHelpers” folder and add the “CustomHelpers.cs” class file. Copy and paste the following code in it. The code is commented and self-explanatory. TagBuilder class is in System.Web.Mvc namespace.

using System.Web;
using System.Web.Mvc;
namespace CustomHTMLHelper.CustomHelpers
{
public static class CustomHelpers
{
public static IHtmlString Image(this HtmlHelper helper, string src, string alt)
{
// Build <img> tag. The parameter name must be img
TagBuilder tb = new TagBuilder("img");
// Add "src" attribute
tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src));
// Add "alt" attribute
tb.Attributes.Add("alt", alt);
// return MvcHtmlString. This class implements IHtmlString
// interface. IHtmlStrings will not be html encoded.
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
}
}
}

To use the custom Image() HTML helper in Details.cshtml view, please include the following using statement in Details.cshtml

@using CustomHTMLHelper.CustomHelpers;

As we intend to use this Image() HTML helper, in all our views, lets include “CustomHTMLHelper.CustomHelpers” namespace in web.config that is present in the Views Folder. This eliminates the need to include the namespace, in each and every view.

<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="TemplateHelpersMVC" />
<add namespace="CustomHTMLHelper.CustomHelpers" />
</namespaces>
</pages>
<host ....../>
</system.web.webPages.razor>

Now use the following code to display an Image

@Html.Image(Model.Photo, Model.AlternateText)

If you intend to use the Image() custom HTML helper, only with a set of views, then, include a web.config file in the specific views folder, and then specify the namespace in it. 

See All

Comments (295 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET MVC / Youtube

What is MVC?

MVC is an architectural software design pattern that is used for developing interactive applications where their user interaction is involved and based on the user interaction some event handling has occurred. It is not only used for web-based applications but it can also be used for Desktop or mobile-based applications where there are user interactions involved.
28-jan-2022 /28 /295

ASP.NET MVC / Youtube

How to Creat First ASP.NET MVC Application using Visual Studio?

In this article, I am going to discuss how to create the first ASP.NET MVC Application step by step from scratch using Visual Studio 2015. You can use any version as per your choice but the step will remain the same. Please read our previous article before proceeding to this article where we gave a brief introduction to ASP.NET MVC Framework.
28-jan-2022 /28 /295

ASP.NET MVC / Youtube

What is ASP.NET MVC File and Folder Structure?

In this article, I am going to discuss the auto-generated ASP.NET MVC File and File Structure when we create a new ASP.NET MVC application. Please read our previous article before proceeding to this article where we discussed how to create ASP.NET MVC 5 application step by step from scratch.
28-jan-2022 /28 /295