Filter by Content Type in Orchard CMS

2019-06-08 21:51发布

I have created a content type "Club" to which i have added part name "Course". i want to get list of Club (content type) in my controller code.

    public ActionResult Index(PagerParameters pagerParameters, CourseSearchVM search)
    {
        //this is displaying only published content
        var courseQuery = _contentManager.Query<CoursePart>().List().ToList();
        // Project the query into a list of customer shapes
        var coursesProjection = from course in courseQuery
                                  select Shape.course
                                  (
                                    Id: course.Id,
                                    Name: course.Name,
                                    Description: course.Description
                                  );

        // The pager is used to apply paging on the query and to create a PagerShape
        var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters.Page, pagerParameters.PageSize);
        // Apply paging
        var coures = coursesProjection.Skip(pager.GetStartIndex()).Take(pager.PageSize);
        // Construct a Pager shape
        var pagerShape = Shape.Pager(pager).TotalItemCount(courseQuery.Count());
        // Create the viewmodel
        var model = new CourseIndexVM(coures, search, pagerShape);
        return View(model);
    }

1条回答
ら.Afraid
2楼-- · 2019-06-08 22:23

You have to get access to IContentManager in your controller, you can do it just adding it to the constructor (see dependency injection, autofac will do the trick). In addition to this you can use IOrchardServices, it will get you access to a few common services (do that if you want to use two of more dependencies from it)

     public MyController(IOrchardServices services){
         this.services = services;
     }

In your action you can do something like this:

     services.ContentManager.HqlQuery()
            .ForType("Club").List()
            .Select(ci => services.ContentManager.BuildDisplay(ci, "Summary"));

The first part will create a list of your ContentType with their content parts, then it just projects the result to a list of shapes, after that, you can attach those shapes to another in order to show the list.

Complete action:

     var clubs = services.ContentManager.HqlQuery()
            .ForType("Club").List()
            .Select(ci => services.ContentManager.BuildDisplay(ci, "Summary"));

        var shape = services.New.ClubList();
        shape.Clubs = clubs;
        return new ShapeResult(this, shape);

This will return a shape with a property Clubs which is the list of shapes that you defined on your Drivers. Note that you have to create a view for ClubList. In your shape ClubList you can display your clubs shapes by doing:

   @foreach (var club in Model.Clubs) {
                    @Display(club)
             }
查看更多
登录 后发表回答