c# blazor 服务器 - 将 class object 从 child 传递到 parent

c# blazor server - pass class object from child to parent



你好

我正在尝试在 Blazor 服务器中制作一个可重用的组件

一个列表框,我在其中传递一个 id(它用来填充自己,然后用户选择的内容被传回

我的想法是将一个 ID 传递给组件,从 parent 到 child,效果很好,但我只能从 child 和我想回一个classobject,可以吗,我试过下面的




parent

@using Microsoft.AspNetCore.Components.Web

@page "/"

@code {

    private void IwasGivendatabackfromclient(HagClass x)
    {
        string text = x.parChildSet;
        
    }


}


<h1>Hello, world!</h1>

Welcome to your new app.

<HagChild GiveMeDatFromPar="Balls of steel" OnEmployeeDeleted="IwasGivendatabackfromclient"></HagChild>



Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Web;

namespace Blazor_PH_Par_Child.Shared
{
    public class HagClass
    {
        public  string parSentMe { get; set; }
        public string parChildSet { get; set; }

    }
}



Child

@code {


    [Parameter]
    public string GiveMeDatFromPar { get; set; }

    [Parameter]
    public EventCallback<object> OnEmployeeDeleted { get; set; }

    HagClass x = new HagClass();

    public void Delete_Click()
    {
        x.parChildSet = "test";

        OnEmployeeDeleted.InvokeAsync(x);
        


        }
}


<h3>HagChild</h3>

<button type="button" class="btn btn-danger m-1"
        @onclick="Delete_Click">
    Delete
</button>

<p>hello @GiveMeDatFromPar</p>

是的,这是可能的。您可以像这样添加参数

[Parameter] 
public EventCallback<MyModel> OnEmployeeDeleted { get; set; }

然后点击删除按钮后,创建Mymodel的item类型,返回给parent

MyModel model = new(){  .... }
OnEmployeeDeleted.InvokeAsync(model);

在父页面中,您必须创建获取子数据的函数。

private void GetDeletedInfo(Mymodel model){}

组件的调用将是

<HagChild OnEmployeeDeleted="data => GetDeletedInfo(data)" />