Replace ChildActionOnly action and partial view with ViewComponent in MVC Core

 Author: Shengtao Zhou       Created: 1/17/2019 2:08:43 AM       Modified: 2/2/2019 5:37:38 AM   More...
MVC Core does not support ChildActionOnly or RenderPartial any more. To implement partial view function, use ViewComponent to achieve the same result.
 According to Microsoft, ViewComponents are more powerful than partial views.

Basically, instead of creating a controller action, you create a ViewComponent class and a view for it. Add the call to the ViewComponent from a View directly.

For example, you want to display a list of posts from the database on a section of your "Home/Index" page, you can use the following steps:

1. Create a "ViewComponents" folder under your MVC Core project.

2. Create a class with name suffix with "ViewComponent. Here, we name it PostsViewComponent.

3. Add inheritance from "ViewComponent" class, or decorate the class with "[ViewComponent]" attribute.

   public class PostsViewComponent : ViewComponent

4. Inject database context in the class constructor

        private readonly ApplicationDbContext _context;
        public PostsViewComponent(ApplicationDbContext context)
            _context = context;

5. Implement Invoke() or InvokeAsync() method and return data with a View

       public async Task InvokeAsync()
            var posts = from c in _context.Posts
                        join u in _context.Users
                            on c.UserId equals u.Id
                        select new PostsViewModel
                            Id = c.Id,
                            Title = c.Title,
                            Slug = Common.ToUrlSlug(c.Title)
            return View(await posts.ToListAsync());

6. Resolve the references in your class to make it compile

7. Add Default.cshtml view in any of these locations,


8. Add data to Default.cshtml view

        @foreach (var item in Model)

9. Call the ViewComponent from Home/Index.cshtml

     @await Component.InvokeAsync("Posts", null)

More...          Back to List          

(Please enter you comments between 100 to 2000 characters. Thanks for your contribution.) 

         Created:       Modified: 

Editing a comment

       (Please enter you comments between 100 to 2000 characters. Please login before edit comment.)