We all know that it is best practice in a responsive world to use SVG, but this is slightly more complicated within the MVC Razor view engine. Since SVG files are recognized as xml files and not image files other steps must be taken. Here are the steps to get SVG working in your MVC Application:
- Add some SVG files to your solution.
I like The Noun Project for my icons so I am using a Factory from Amelia Wattenberger. There are a lot of sources for getting and or making your own SVG. I’ve talked about them previously, and I recommend Inkscape since it is very full featured, free, and has plenty of good tutorials. I have also found it helpful to build out the raw image in Power Point and then go to image.online-convert.com to convert your simple image to something that is closer to what your looking for..
- Add this Helper to your Solution:
- Add this where Where you want your SVG to be Displayed. at this point it becomes a bit of a preference discussion. However the standard for choosing which tag to use tag seems to be: prefer object over embed. The helper above is to include the svg in the rendered HTML (without either the object or embed). The reason I choose this approach is multi-fold:
- The object/embed approach is simple enough that you don’t really need the overhead of an Html Helper.
- The helper can get inside the XML and make modifications on the SVG which makes it more extensive.
- Syntactically it is more in “tune” with the Razor View Engine.
- Better to reduce/reuse code.
here is how you would use the HTML Helper:
And here is a comparison of the footprint of all three approaches:
It is easy to see that the HtmlHelper is a good compramise between the verbose and hard to maintain XCopy of the SVG XML into the cshtml file. and it is also shorter than the object approach.
I hope this helps you Happy Coding.