In JavaScript one can load a view into a specific container or div like using $("#div1").load("/Home/GetPartial"). How do I achieve the same in Blazor where I want to be able to specify which div in a page gets loaded with a view/component and also pass parameter along.
1 Answers
Rendering a Blazor component conditionally on a MVC or Razor Page
The RenderComponentAsync method can be used to render a Blazor component onto an MVC or Razor page in a specific location.
You can then use conditional rendering in the same way as you would in normal MVC/Razor to determine where on the page the component should be rendered.
In the example below my Razor Page has a property called CaseId in its code behind model, but that could equally be a variable declared in the code section of on an MVC page and retrieved from the parameters of the URL.
<div class='new-column'>
@if (Model.Status = "New")
{
@(await Html.RenderComponentAsync<SprintCase>(RenderMode.Server,
new { CaseId = Model.CaseId }))
}
</div>
<div class='in-progress-column'>
@if (Model.Status = "In Progress")
{
@(await Html.RenderComponentAsync<SprintCase>(RenderMode.Server,
new { CaseId = Model.CaseId }))
}
</div>
<div class='complete-column'>
@if (Model.Status = "Complete")
{
@(await Html.RenderComponentAsync<SprintCase>(RenderMode.Server,
new { CaseId = Model.CaseId }))
}
</div>
That should work for getting the component rendered into the correct location on first load.
If you then want to dynamically update the MVC/Razor page, without reloading the whole page, I think you should be able to that in the same way as you would normally with a partial view in MVC, i.e. have a controller endpoint that returns a partial view that contains the code above and that should render in the same way as if the partial was just returning HTML. I haven't tried that so I'm not completely certain.
You'll also need to get Blazor running in your MVC app, there's more on that here.
Rendering a Blazor component conditionally in another Blazor component
This case is much simpler, you simply need a property in either your component's @code block, or some other property to perform the switch on. Whenever that property changes the component should then re-render automatically, but if it doesn't you can give it a prompt by calling StateHasChanged
<div class='new-column'>
@if (Model.Status = "New")
{
<SprintCase CaseId=Model.CaseId />
}
</div>
<div class='in-progress-column'>
@if (Model.Status = "In Progress")
{
<SprintCase CaseId=Model.CaseId />
}
</div>
<div class='complete-column'>
@if (Model.Status = "Complete")
{
<SprintCase CaseId=Model.CaseId />
}
</div>
@code {
private SprintCase Model { get; set; }
}
Where SprintCase is the name of the Blazor component you want to conditionally render.
I've written a lot more about dynamic/conditional component rendering in this answer too.