I have created a layout component in the same directory as with the MainLayout component. The CustomLayout @inherits LayoutComponentBase
and has @Body
which gets the content to be rendered inside the layout.
As obviously expected, the layout component has its own css files and UI display is fine. I am only having a problem with the @onclick function
. It cannot be invoked. Is there a way to trigger the function on button click?
The reason I want to do this is that I am creating a navigation bar which will have to show/hide a dropdown. I hope I can get some ideas on this. Appreciated.
I am calling a server function this way: @onclick="SomeFuction"
or @onclick="SomeFuction" or @onclick="@(() => SomeFuction())"
LayoutComponent:
@inherits LayoutComponentBase
@Body
Home page referencing a custom layout:
[AllowAnonymous]
[Layout(typeof(CustomLayoutComponent))]
[AllowAnonymous]
is just for allowing anonymous access.
I am using Blazor Server and .NET 6
Additional Information: I have put all the code in one page so that it becomes easier to read and understand.
Here is the LayoutComponent razor component:
@inherits LayoutComponentBase
<div class="navbar" id="custom-navbar">
<div class="wrapper">
<a>Home</a>
<a>Service</a>
<button class="btn btn-primary" @onclick="ToggleProductsUI">Products</button>
</div> </div>
<!--Component to show Products UI Component. Scoped css for styling-->
<ProductsComponent TValue="string" UIState="@ProductsUIState"></ProductsComponent>
@code{
// state of the Products submenu Component
string ProductsUIState { get; set; }
// a control function for toggling the Products UI
// this function somehow is not invoked.
void ToggleProductsUI()
{
if (string.IsNullOrWhiteSpace(ProductsUIState))
{
ProductsUIState = "show-ui";
return;
}
ProductsUIState = string.Empty;
}
}
Here is the ProductsUI component code (I have removed the unnecessary event to avoid confusion. The component can be fully controlled by the parent):
public partial class ProductsComponent<TValue> {
[Parameter]
public string? UIState { get; set; } }
Blazor pages that will use the custom layout component will point to it like this:
[AllowAnonymous]
[Layout(typeof(CustomLayoutComponent))]
public partial class Index
{
}
This is working fine. The issue is in the CustomLayoutComponent when trying to invoke the ToggleProductsUI()
function
I accidentally inluded a
<body>
element in the layout and as such, the<script src="_framework/blazor.server.js"></script>
was not being run hence the click event was not being invoked. I removed the<body>
element. I was misled by the defaultbody{}
style in the underlining scopped css. Resolved.