C# HtmlExtension to display SVGs

C

You have SVGs that you wish to display on your website but you want to be able to re-use them without copying and pasting the code or creating a shared view.

By creating an HtmlExtension class with a function called Svg you can create a centralized place to store and re-use your SVGs.

I’m turning into a big fan of extension classes as I discussed when creating a string extension for my HasValue function.

Creating an Html Extension

To begin I will create a skeleton HtmlExtension class with the Svg function. The function will accept a string as input which will be a unique name for your SVG. This will allow you to easily expand this class to display many different SVGs by passing in a different SVG name.

[code]
using System.Web.Mvc.Html;

namespace System.Web.Mvc
{
public static class HtmlExtensions
{
public static IHtmlString Svg(this HtmlHelper htmlHelper, string svgName, int width = 50, int height = 50)
{
var svg = string.Empty;

return new HtmlString(svg);
}
}
}
[/code]

Next, let’s expand this class to return different SVGs. For simplicities sake, I will use a switch statement which is similar to a CASE Statement in SQL for each SVG name.

I have also added two optional parameters: width and height. These parameters allow for easily changing the height of the SVG on a per implementation basis.

[code]
using System.Web.Mvc.Html;

namespace System.Web.Mvc
{
public static class HtmlExtensions
{
public static IHtmlString Svg(this HtmlHelper htmlHelper, string svgName,int width = 50,int height = 50)
{
var svg = string.Empty;

switch (svgName.ToLower())
{
case “calendar”:
svg = string.Format(@”” +
” +
Calendar” +
@”” +
@”” +
” +
“”, width, height);
break;

case “checkmark”:
svg = String.Format(@”

Default

“, width, height);
break;
}

return new HtmlString(svg);
}
}
}
[/code]

@Html.Svg in your Razor View

In the above example there are two svgs created: calendar and check. After this extension class is created, inside your Razor templates (cshtml) you can use it as follows: @Html.Svg(“calendar”). This not only makes it easy to globally change an svg, but it makes your views contain less code for readability.

About the author

By Jamie

My Books