Search code examples
c#jsonasp.net-coreasp.net-core-mvcasp.net-core-viewcomponent

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.


Solution

  • 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));
    }