loading...

CshtmlComponent V2.2.0 - Reference Capturing

acmion profile image Acmion ・2 min read

CshtmlComponent is a component library for ASP.NET Core with an advanced feature set. These features significantly improve developer productivity in MVC or Razor Pages projects. Check out the CshtmlComponent documentation for more information.

Previously with CshtmlComponent, you could write Razor code like this:

<ExampleComponent Title="Some title" font-size="1.2rem" background-color="rgba(0, 0, 255, 0.1)">
    <div>
        Some custom HTML content.
        <Box>
            Supports nested components.
        </Box>
    </div>
    <CshtmlSlot Name="SlotName0">
        Some custom HTML content within a named slot. The parent component decides where
        this content is placed.
    </CshtmlSlot>
    <CshtmlSlot Name="SlotName1">
        Additional custom HTML content within a second named slot.
        <Box>
            Supports nested components.
        </Box>
    </CshtmlSlot>
</ExampleComponent>

The component themselves can always access their own properties, but what if you want to access the properties outside the component's own context? For example, one might need to get a generated ID value to use it in some JS code. This is now possible with CshtmlComponent V2.2.0, where you now can capture the component reference like this:

<ExampleComponent Title="Some title" font-size="1.2rem" background-color="rgba(0, 0, 255, 0.1)">
    <div>
        Some custom HTML content.

        @{ 
            // Assign a variable to component reference. 
            // The Box component inherits CshtmlComponentReferenceableBase<Box> (a class that inherits CshtmlComponentBase), 
            // which implements this logic. Useful if component properties have to be used outside the component's own context.

            // This is not the default behavior due to the mandatory, but slightly confusing syntax: 
            // public Box : CshtmlComponentReferenceableBase<Box> ....

            var boxReference = new CshtmlComponentReference<Box>();
        }
        <Box Reference="boxReference">
            Supports nested components.
        </Box>

        The fontsize of the referenced box is: @boxReference.Component.FontSize
    </div>
    <CshtmlSlot Name="SlotName0">
        Some custom HTML content within a named slot. The parent component decides where
        this content is placed.
    </CshtmlSlot>
    <CshtmlSlot Name="SlotName1">
        Additional custom HTML content within a second named slot.
        <Box>
            Supports nested components.
        </Box>
    </CshtmlSlot>
</ExampleComponent>

CshtmlComponent documentation: https://cshtml-component.acmion.com

CshtmlComponent GitHub: https://github.com/Acmion/CshtmlComponent

CshtmlComponent Nuget: https://www.nuget.org/packages/Acmion.CshtmlComponent/

Discussion

pic
Editor guide