Fri. Dec 6th, 2019

Host your Website

Read and learn

FatCow Web Hosting $1.00/mo* Trust your web hosting to the #1 web host provider, GoDaddy!

Part 48 Custom html helpers in mvc

2 min read



In this video, we will discuss, creating custom html helpers. We will be using the example, that we worked with in Part 47. Please watch Part 47, before proceeding.

In Part 47, to render the image, we used the following code. We are building the image tag, by passing 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 it’s own helper method. We don’t want any complicated logic in our views. Views should be as simple as possible. Don’t you think, it would be very nice, if we can render the image, using Image() html helper method as shown below. Unfortunately, MVC does not have built-in Image() html helper. So, let’s build our own custom image html helper method.
@Html.Image(Model.Photo, Model.AlternateText)

Let’s take a step back and understand html heper 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.

Let’s now add, Image() extension method, to HtmlHelper class.
1. Right click on MVCDemo project and add “CustomHtmlHelpers” folder.
2. Right click on “CustomHtmlHelpers” folder and add “CustomHtmlHelpers.cs” class file.
3. Copy and paste the following code. The code is commented and self-explanatory. TagBuilder class is in System.Web.Mvc namespace.
namespace MVCDemo.CustomHtmlHelpers
{
public static class CustomHtmlHelpers
{
public static IHtmlString Image(this HtmlHelper helper, string src, string alt)
{
// Build IMG tag
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 folowing using statement in Details.cshtml
@using MVCDemo.CustomHtmlHelpers;

As we intend to use this Image() html helper, in all our views, let’s include “MVCDemo.CustomHtmlHelpers” namespace in web.config. This eliminates the need to include the namespace, in every view.

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

Text version of the video
http://csharp-video-tutorials.blogspot.com/2013/07/part-48-custom-html-helpers-in-mvc.html

Slides
http://csharp-video-tutorials.blogspot.com/2013/09/part-48-custom-html-helpers-in-mvc.html

All ASP .NET MVC Text Articles
http://csharp-video-tutorials.blogspot.com/p/aspnet-mvc-tutorial-for-beginners.html

All ASP .NET MVC Slides
http://csharp-video-tutorials.blogspot.com/p/aspnet-mvc-slides.html

All Dot Net and SQL Server Tutorials in English
https://www.youtube.com/user/kudvenkat/playlists?view=1&sort=dd

All Dot Net and SQL Server Tutorials in Arabic
https://www.youtube.com/c/KudvenkatArabic/playlists

18 thoughts on “Part 48 Custom html helpers in mvc

  1. The Visual Studio does behave weirdly while in this case when we add an extension method and add reference in webconfig, but to fix the intellisence error we can just close the view and reopen it, no need to reopen the complete solution

  2. Interesting way to do it. I have always done it like so to do the same thing,
    public static class ImagePlaceholder
    {
    /// <summary>
    /// Create an img tag for displaying an image.
    /// </summary>
    /// <param name="HTMLHelper"></param>
    /// <param name="ImageLocation">The string location of the image to display.</param>
    /// <param name="AltText">The ALT and TITLE text to display for the image.</param>
    /// <param name="HTMLAttribs">Any additional HTML attributes. Default is null.</param>
    public static MvcHtmlString Image(this HtmlHelper HTMLHelper,
    string ImageLocation,
    string AltText,
    object HTMLAttribs = null)
    {
    TagBuilder BuildImgTag = new TagBuilder("img");
    BuildImgTag.Attributes.Add("src", ImageLocation);
    BuildImgTag.Attributes.Add("alt", AltText);
    BuildImgTag.Attributes.Add("title", AltText);
    BuildImgTag.MergeAttributes(new RouteValueDictionary(HTMLAttribs));

    return MvcHtmlString.Create(BuildImgTag.ToString(TagRenderMode.Normal));
    }

    /*
    Usage in Razor:
    @Html.Image(Url.Content( "~/Content/images/img.png"),
    "alt text",
    new { id = "myImage", border = "0" } )
    */
    }

  3. This does not work for me. I keep getting the following error: Compiler Error Message: CS1928: 'System.Web.Mvc.HtmlHelper<dynamic>' does not contain a definition for 'Image' and the best extension method overload 'MVC5.CustomHtmlHelpers.CustomHtmlHelpers.Image(System.Web.HtmlString, string, string)' has some invalid arguments.

    **Index.cshtml:**

    @Html.Image("~/Content/1.jpg", "altText")

    **CustomHtmlHelpers.cs:**

    using System;
    using System.Web;
    using System.Web.Mvc;

    namespace MVC5.CustomHtmlHelpers
    {
    public static class CustomHtmlHelpers
    {
    public static IHtmlString Image(this HtmlString helper, String src, String alt)
    {
    TagBuilder tb = new TagBuilder("img");
    tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src));
    tb.Attributes.Add("alt", alt);
    return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
    }
    }
    }

  4. Just regarding the Intellisense bug: I believe you can force Intellisense to refresh using ctrl+shift+J. You can also access the Intellisense refresh function by clicking on Edit -> Intellisense -> Refresh Remote References.

  5. Use paging and display only 10 or 20 images at a time, depending on your requirement. Hope this helps. For email alerts, please subscribe to my channel. In the description of this video, I have included the link for ASP .NET, C#, and SQL Server playlists. All the videos are arranged in logical sequence in these playlists, which could be useful to you. Please share the link with your friends. If you like these videos, please click on the THUMBS UP button below the video.

  6. Videos 47 and 48 are short and sweet and we need not spend lots of time to learn. It's sharp and crisply explained. I enjoyed this video and also I recommend for watching for learning. Thanks a bunch

Comments are closed.

Copyright © All rights reserved. | Newsphere by AF themes.