Serializing Form Data in MVC using Json.NET

I recently worked on a project where we designed a web application to submit a form to a certain dreaded government agency. We needed to load the form data into SQL Server and retrieve it, in case the customer’s application was rejected. My co-developer suggested Json–I was initially doubtful, since SQL Server has a ton of support for XML but very little for Json.

It ended up being super easy to use Json, maybe the smoothest part of the project aside from Stripe integration. We leveraged the Json.NET library and the view model approach. Here is how we did it:

In your Models, create a view model for your form data:

namespace MyApp.ViewModels
public class FormViewModel
public string LastName {get; set;}
public string FirstName {get; set;}
public string SomeMoreFormData{get; set;}


Then create another model for your application domain data that matches your database table.

namespace MyApp.Models
public class ApplicationModel
public Guid ID {get; set;}
public Guid CustomerID {get; set;}
public string FormViewJson {get; set;}

In your form POST method, grab the ViewModel (if valid) and serialize it using Json.NET.

string _formViewJson= JsonConvert.SerializeObject(_formViewModel);

Then map it to your FormViewModel property in your ApplicationModel, and load it into the DB with the ORM of your choice (we used Dapper, which was great btw).

When the customer returns and needs to access their form data again, just grab the FormViewJson from the DB, and deserialize it into FormViewModel, like this:

_formViewModel = JsonConvert.DeserializeObject<FormViewModel>(_applicationModel.FormViewJson);

Pass _formViewModel in your “update form” GET controller method to a strongly typed view and voila! You have the customer’s previous form data rendered.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s