简体   繁体   中英

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.

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();
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM