HtmlHelper Extenstion to convert HTML to JSON C#

H

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 to convert with C# HTML to JSON.

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:

[code]
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);
}
}
}
[/code]

Now to fill in the details; similar to how I’ve done it with converting a date with C#. 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 JavaScript arrays.

[code]
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));
}
}
}
[/code]

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

[code]

[/code]

Other useful articles

About the author

By Jamie

My Books