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.
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.
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.
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With