Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return JSON from a View Component?

I am trying to move controller logic into a view component class, but the controller only returns JSON, for a client side widget that is the UI of my view component. This is the core controller code where the problem is:

public IActionResult TreeData(string dir = "")
{
    var browsingRoot = Path.Combine(_config.BaseDir, dir);
    var nodes = new List<TreeNode>();
    nodes.AddRange(RecurseDirectory(browsingRoot));
    return Json(nodes);
}

This is fine in the controller, but the ViewComponent derived class doesn't like the Json return method. All examples I see use return View(*<something>*).

View components are not supposed to return entire responses, so I would imagine it should rather have a Content return method to return pure HTML at least.

like image 332
ProfK Avatar asked Oct 09 '17 06:10

ProfK


People also ask

Can we return JSON through view result?

The Controller consists of two Action methods. Inside this Action method, simply the View is returned. This Action method handles the call made from the jQuery POST function from the View. Note: The following Action method handles POST call and will return JSON object and hence the return type is set to JsonResult.

How do I return a JSON response in C#?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header.


1 Answers

It looks like it can be done by returning content, not a view:

public IActionResult TreeData(string dir = "")
{
    var browsingRoot = Path.Combine(_config.BaseDir, dir);
    var nodes = new List<TreeNode>();
    nodes.AddRange(RecurseDirectory(browsingRoot));
    return new ContentViewComponentResult(JsonConvert.SerializeObject(nodes));
}
like image 60
ProfK Avatar answered Sep 17 '22 16:09

ProfK