简体   繁体   English

.net core Blazor 动态渲染cshtml局部视图组件

[英].net core Blazor render cshtml partial view component dynamically

In my blazor .razor component I have this code...在我的 blazor .razor组件中,我有这个代码......

... stuff ...

@HistoricDeck

... stuff ...

@code
{
    protected GameDataModel GameData { get; set; }

    protected RenderFragment HistoricDeck { get; set; }

    protected async Task LoadDeck(FriendSupportModel deck, DeckType type)
    {
        HistoricDeck = builder =>
        {
            var deckFragment = new SupportDeck() {
                GameData = GameData,
                AssetList = GameData.AssetList,
                Deck = deck.normalDeck,
                Type = DeckType.Standalone,
            };
            builder.OpenElement(0, "div");
            builder.AddAttribute(1, "SupportDeck", deckFragment);
            builder.CloseElement();
        };
        StateHasChanged();
    }
}

LoadDeck is called by an @onclick= event on the page, I wish to dynamically render a new SupportDeck() into the page. LoadDeck 由页面上的@onclick=事件调用,我希望将新的 SupportDeck() 动态呈现到页面中。 How do I do this?我该怎么做呢? The code below is non-functional (breakpoints in SupportDeck.cshtml are not hit, for example).下面的代码是非功能性的(例如,SupportDeck.cshtml 中的断点没有被命中)。

SupportDeck.cshtml.cs: SupportDeck.cshtml.cs:

public class SupportDeck
{
    public FriendServantListModel Deck { get; set; }
    public DeckType Type { get; set; }
    public GameDataModel GameData { get; set; }
    public AssetList AssetList { get; set; }
}

SupportDeck.cshtml: SupportDeck.cshtml:

@model Project.Views.Shared.SupportDeck
... stuff ...
@if (Model.Deck != null) {
<p>Hello world</p>
}
... stuff ...

Here is how I would normally render this view fragment in a non-blazor page:以下是我通常在非 Blazor 页面中呈现此视图片段的方式:

@{
    await Html.RenderPartialAsync("SupportDeck", new SupportDeck
    {
        Deck = Model.FriendSupport.normalDeck,
        Type = DeckType.Normal,
        GameData = Model.GameData,
        AssetList = Model.AssetList
    });
}

Solved by turning the .cshtml into a .razor template, then this:通过将.cshtml转换为.razor模板来解决,然后:

        HistoricDeck = builder =>
        {
            builder.OpenComponent(0, typeof(SupportDeckItem));
            builder.AddMultipleAttributes(1, new Dictionary<string, object>() {
                {"Deck", deck},
                {"Type", deckType},
                {"GameDataItem", gameData},
                {"AssetList", gameData.AssetList}
            });
            builder.CloseComponent();
        };
        StateHasChanged();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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