2

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

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

public ActionResult Index() { return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = db.someData, ContentType = "text/html", }; } //Thanks ...This is how I got it working...So return type ActionResult vs JsonResult which is better? both is working though
You can use both but I would suggest use JsonResult. Avoid returning the generic ActionResult as much as possible and return the concrete types like ViewResult, JsonResult and such.
2
var jsonData = @Html.Raw(new JavaScriptSerializer().Serialize(Model));

Here is MSDN documentation for JavaScriptSerializer Class.

1 Comment

I will go through the doc and try this..Thanks a lot
0

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.

1 Comment

May be I am not clear in my question.But I actually wanted to know how to convert the data to JSON in controller...I got it working now...using JsonResult in controller.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.