Jun 1, 2011

Part 1 : Convert Object into JSON Data Type - MVC 3



Today I would like to share a simple tips on how to bind object data which we retrieve from model or SQL into Json type of data so that we could manipulate the objects to be include into JS function.

For example, I'm using SQL and my Model in MVC 3 is using LINQ-to-SQL(Which I name it as negativeZeroDB).  So I will fetch all records in SQL database NegativeZero from table POST into an object variable we named it as dataObject.  Below is the code on how I retrieve my object.
var db = new negativeZeroDBDataContext(); 
// First I need to declare my LINQ on variable db
var dataObject = db.POST;
// This line will fetch all records in table POST.
Now, we do have an object with all records from table POST inside dataObject.  There is a differences between Json and Object data if we look on the inside.  For example, dataObject data will look a bit like this:
dataObject = { ID = 0; TITLE = "TITLE";}
//while Json data look just like below
dataJson = {'0','TITLE'}
In order to bind dataObject into Json, we just need simple codes which stated below:
// In Controller, create this function
public ActionResult convertObjectJson(object y)
{
              return Json(y);
}
Right now, this only could be execute in MVC3 controller.


Thank you for your unbelievable support on Negative Zero - Permission to read and write blog for nearly 4 years. Don't forget to like Negative Zero on Facebook.
Blogirific.com Blog Directory





Post(s) you might like to read :

Comments
0 Comments

0 comments:

Post a Comment