#ASP.NET CORE-View Components

What is View Components ?

ViewComponents are similar to partial view,that helps you to write reusable components.

Definition According to documentation:

New to ASP.NET Core MVC, view components are similar to partial views, but they are much more powerful. View components don’t use model binding, and only depend on the data you provide when calling into it.

View Components :

ViewComponents consists of two parts

1.Class derived from ViewComponent.

2.Result  returned from ViewComponent typically a view.

Creating a View-Component :

Let’s create a simple view component. They can be created in any of  ways listed below,

1.Derived from View Component class.

2.Decorate with ViewComponent Annotation.

3.class suffixed with ViewComponent.

A sample View Component would look like below:


public class SimpleViewComponent : ViewComponent
{
public IViewComponentResult Invoke()
{
return View();
}

}

Creating a View for ViewComponent :

The runtime searches for the view in the following paths:

  • Views/<controller_name>/Components/<view_component_name>/<view_name>
  • Views/Shared/Components/<view_component_name>/<view_name>

Let’s create a sample view named Default.cshtml which says “Hello Simple View Component” in the shared folder for the viewcomponent.

Capture

Invoking ViewComponent in the view : 

ViewComponent can be be called from view using @Components synchronously/asynchronusly with viewcompanent name.


@await Component.InvokeAsync("Simple")

You can download the sample code from github below

https://github.com/rangesh-/ViewComponents-.NET-CORE

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s