I am using jQuery datatables. This tutorial http://www.codeproject.com/Articles/165410/ASP-NET-MVC-Editable-DataTable-jQuery-DataTables-a shows how to call a controller action, using datatable. But, datatable expects a json response and I have a partial view to load the table rows. How to convert a ASP.NET MVC5 Razor (Partial)View(.cshtml) to JSON? Ideally using Newtonsoft.Json but other libraries will work.
I could load html table using json as shown in the tutorial
$(document).ready(function () {
$("#example").html();
$("#example").DataTable({
"processing": true, // for show progress bar
"serverSide": true, // for process server side
"filter": false, // this is for disable filter (search box)
"orderMulti": false, // for disable multiple column at once
"ajax": {
"url": "/home5/AjaxGetJsonData",
"type": "GET",
//"datatype": "html"
"datatype": "json"
}
,
"columns": [
{ "data": "Name", "name": "ContactName", "autoWidth": true },
{ "data": "Age", "name": "CompanyName", "autoWidth": true },
{ "data": "DoB", "name": "Phone", "autoWidth": true }
]
});
});
With the controller returning
return Json(dataTableData, JsonRequestBehavior.AllowGet);
I want to do something like
PartialViewResult searchView = PartialView("Search", model);
return Json(JsonConvert.SerializeObject(searchView));
I also tried converting the partial (.cshtml) view to string using below as the accepted answer here Render a view as a string
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View,
ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}