Orchard CMS - Returning HTML in API call

391 Views Asked by At

I Created a custom module in Orchard CMS (1.10) which exposes an API endpoint. I would like to expose a Get call where if I pass the ID of a Content Item it returns the Html of that Content Item.

I also would like to know how can I return the Page layout html in API call as well?

Thank you

2

There are 2 best solutions below

1
Bertrand Le Roy On

I'm pretty sure what you're asking is exactly what the Display method of the ItemController in Orchard.Core.Contents.Controllers is doing:

public ActionResult Display(int? id, int? version) {
    if (id == null)
        return HttpNotFound();

    if (version.HasValue)
        return Preview(id, version);

    var contentItem = _contentManager.Get(id.Value, VersionOptions.Published);

    if (contentItem == null)
        return HttpNotFound();

    if (!Services.Authorizer.Authorize(Permissions.ViewContent, contentItem, T("Cannot view content"))) {
        return new HttpUnauthorizedResult();
    }

    var model = _contentManager.BuildDisplay(contentItem);
    if (_hca.Current().Request.IsAjaxRequest()) {
        return new ShapePartialResult(this,model);
    }

    return View(model);
}

The view's code is this:

@using Orchard.ContentManagement
@using Orchard.Utility.Extensions
@{
    ContentItem contentItem = Model.ContentItem;
    Html.AddPageClassNames("detail-" + contentItem.ContentType.HtmlClassify());
}@Display(Model)
0
mdameer On

I think this what you need:

public class HTMLAPIController : Controller {
    private readonly IContentManager _contentManager;
    private readonly IShapeDisplay _shapeDisplay;
    private readonly IWorkContextAccessor _workContextAccessor;

    public HTMLAPIController(
        IContentManager contentManager,
        IShapeDisplay shapeDisplay,
        IWorkContextAccessor workContextAccessor) {
        _contentManager = contentManager;
        _shapeDisplay = shapeDisplay;
        _workContextAccessor = workContextAccessor;
    }

    public ActionResult Get(int id) {
        var contentItem = _contentManager.Get(id);

        if (contentItem == null) {
            return null;
        }

        var model = _contentManager.BuildDisplay(contentItem);

        return Json(
            new { htmlString = _shapeDisplay.Display(model) }, 
            JsonRequestBehavior.AllowGet);
    }

    public ActionResult GetLayout() {
        var layout = _workContextAccessor.GetContext().Layout;

        if (layout == null) {
            return null;
        }

        // Here you can add widgets to layout shape

        return Json(
            new { htmlString = _shapeDisplay.Display(layout) }, 
            JsonRequestBehavior.AllowGet);
    }
}