Ajax3.14
Ajax3.14

Reputation: 1695

Converting to JSON For Jquery tables in MVC

I am writing a application in MVC with a existing database. I succesfully connected the DB with EF and through Scaffolding. The tables are displayed in the view.

I wanted Jquery plugin, Datatable for sorting and filtering. But they require the data in JSON format. I looked around and do not find a solid way to convert the values from existing database to JSON.

I see tutorials where WebAPI attributes like DBController and DataService are added and converted to JSON. I cannot able to work it through this way...

SO I was wondering ways of how to convert the values getting in views to JSON..I am sorry if I added lot of unwanted information.

Thanks a lot

Upvotes: 2

Views: 1384

Answers (3)

Bishnu Paudel
Bishnu Paudel

Reputation: 2079

Your Jquery DataTable sits in View and we should always avoid processing of data inside view. View should only display the data that is passed from the Controller.

Having said this, you should create a method in the controller which returns the result as Json object as Mark suggested.

Upvotes: 0

VJAI
VJAI

Reputation: 32768

If you want to do the JSON conversion in view then you can follow what @Aleksey answered. You told you are using jquery plugin(jquery table?) so you may need controller actions that will return the data to fill the grid as JSON? In this cases you can have actions in controller that returns Json action result and you don't need to do any conversion by directly using JavaScript serializer (this will be done by the framework for you).

For ex.

public JsonResult GetDataToFillGrid(parameters)
{
  var dataCollection = .. get from db

  return Json(dataCollection, JsonRequestBehavior.AllowGet);
}

JsonRequestBehavior.AllowGet you have to use for GET requests.

Upvotes: 2

Aleksey Cherenkov
Aleksey Cherenkov

Reputation: 1485

var jsonData = @Html.Raw(new JavaScriptSerializer().Serialize(Model));

Here is MSDN documentation for JavaScriptSerializer Class.

Upvotes: 2

Related Questions