Helping you solve those tough coding problems!

HtmlHelper Extenstion to convert an object to JSON with C# HtmlHelper Extenstion to convert an object to JSON with C#

Published on Apr 10, 2019 by Jamie Munro

Let's create an HTML Extension for C#'s HtmlHelper class that converts a class or object to JSON for use with your JavaScript code. I use this in my MVC projects inside my Razor Views. The solution leverages NewtonSoft's JsonConvert NuGet package.




By creating an HtmlExtension you can create a common function that accepts an object and NewtonSoft to convert the object to a HtmlString of JSON data.

Using JsonConvert.SerializeObject to get me some JSON



To start, let's create our HtmlExtension class with a function called ConvertToJson. This function will accept an object and return an HtmlString:


using System.Linq.Expressions;
using System.Reflection;
using System.Web.Mvc.Html;
using Newtonsoft.Json;

namespace System.Web.Mvc
{
    public static class HtmlExtensions
    {
        public static HtmlString ConvertToJson(this HtmlHelper htmlHelper, object model, bool escapeHtml = false)
        {
            return new HtmlString(string.Empty);
        }
    }
}


Now to fill in the details. To convert the object I will use the JsonConvert.SerializeObject. I will also define some basic settings for the conversion that I find useful: ReferenceLoopHandling = ReferenceLoopHandling.Ignore. This will ensure we don't end up in endless loops if our object contains circular references back to each other. The other setting Formatting = Formatting.Indented. This setting will make the returned JSON data indented. This is useful when our object contains multiple child objects or arrays.


using System.Configuration;
using System.Linq.Expressions;
using System.Reflection;
using System.Web.Mvc.Html;
using Newtonsoft.Json;

namespace System.Web.Mvc
{
    public static class HtmlExtensions
    {
        public static HtmlString ConvertToJson(this HtmlHelper htmlHelper, object model, bool escapeHtml = false)
        {
            var settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Formatting = Formatting.Indented };

            return new HtmlString(JsonConvert.SerializeObject(model, settings)); 
        }
    }
}


And finally to use this code from your Razor template (cshtml):



Tags: ASP.NET | c# | htmlextension | json

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP