C# Utility methods for javascript data
I try to setup more of a Single Page Application type approach on newer projects but sometimes things just get in the way of fully utilizing a javascript framework such as backbone.js. Deadlines, management decisions or a particularly gnarly data model can cause the need for a quick and simple solution for getting a simple object from the server to the front end.
Here are a couple of methods I use:
https://gist.github.com/3994708
The first is a simple but quick ToJson() extension that works great for feeding simple objects to ajax calls. Just don't try it with a dictionary, hashtable or similar un-serializable datastructures, it'll just bomb.
ex:
return Content(new { status = true, returnData = someData }.ToJson());
The second is a quick helper method for dumping an object to html 5 data attributes using a generic method and reflection. I wasn't able to find a way to do this in a simpler extension, if anyone knows of a more elegant solution let me know
ex.
<div class="cartItem"
@(Html.Raw(DataHelper.ObjectToHtmlData<CartItem>(item)))>
...
</div>