'Blazor - Need to create pages dynamically

In my App, I wanted to create N number of Pages where each Page may have a different set of controls(which are again dynamically populated).

Here is the flow, I will choose a file that will say how many pages and for each page what are the controls to be populated.

for e.g., below are the contents of the file.

# of Pages = 2

Page 1:
# of controls =3
Control1.Name ="A"
Control1.type = Dropdown
Control2.Name = "B"
Control2.type ="Textbox"
Control3.Name = "C"
Control3.type ="Textbox"

Page 2:
# of controls = 1
Control1.Name ="X"
Control1.type = Dropdown

I have created a Blazor Page and have written the HTML code to populate the controls dynamically. But I am not sure how to create the Blazor pages dynamically so that in my case, I can create two pages.

Any inputs would be helpful.



Solution 1:[1]

I would take your code:

I have created a Blazor Page and have written the HTML code to populate the controls dynamically

and create a Component that takes a parameter that distinguishes your page content. I have used PageNumber as your question implies this.

@page "/dynamicPage/{PageNumber:int}"

<SomeDynamicContentMaker Page=@PageNumber />

@code 
{ 
    [Parameter]
    public int PageNumber { get; set; }
}

You could do this all in one page component but I like to break things down into no more than one or two concerns.

Solution 2:[2]

Actually, the problem is that there are too many ways to do this. I suspect that first you'll really need to say WHY you want to do this. Blazor is very good at modularizing components, and you can already have any arbitrary content you want, in any component or page, as is.

Since Blazor is all about conditional logic, I recommend building a page with a simple switch:

MyPage.razor

@switch (Pagetype){
     case 1:  <MyCustomDropdown Rows=@RowData />
         break;
     case 2:  <MyCustomTextbox Title=@Title  />
         break;
}

@code {
    [Parameter]
    public int Pagetype {get; set;}
}

You could also consider looking up how to use Dynamic Components in Blazor: https://docs.microsoft.com/en-us/aspnet/core/blazor/components/dynamiccomponent?view=aspnetcore-6.0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brian Parker
Solution 2 Bennyboy1973