Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render Razor Partial View in Razor Component (Blazor)

I am newly discovering Blazor and have been playing with some test projects to better gauge how I might include this in future projects. Coming from an MVC background I have started with an MVC project and added Razor components to it which I am nesting inside of my standard MVC razor pages.

Is the reverse possible? Can I do something equivalent to @Html.RenderPartial() inside of a Razor(Blazor) component?

For example

MVC View uses @(await Html.RenderComponentAsync<Test>(RenderMode.ServerPrerendered)) to render a component

The component manages state etc and uses an equivilent of @Html.RenderPartial("Someview.cshtml", someModel) to render standard razor view with model binding.

like image 866
Jarmez De La Rocha Avatar asked May 27 '26 23:05

Jarmez De La Rocha


1 Answers

You can use a RenderFragment to load an Html code from a static file, razor page or MVC view by loading its content from its URL.

sample

@page "/"
@page "/home"
@inject HttpClient _httpClient

<h1>Welcome</h1>
@_renderFragment

@code {
        protected override async Task OnInitializedAsync()
        {
            using var response = await _httpClient.GetAsync("http://localhost:4321/WelcomFragment").ConfigureAwait(false);
            var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            _renderFragment = builder =>
            {
                builder.OpenElement(1, "p");
                builder.AddContent(2, new MarkupString(content));
                builder.CloseElement();
            };
            base.OnInitialized();
        }
}
like image 90
agua from mars Avatar answered May 30 '26 13:05

agua from mars



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!