HtmlHelper Extenstion to convert HTML to JSON C# HtmlHelper Extenstion to convert HTML to JSON C#

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:


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; 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.


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):



Published on Apr 10, 2019

Tags: ASP.NET MVC and Web API Tutorial | c# | htmlextension | json

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.