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>
Written by Stacy Gay
Related protips
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside