简体   繁体   中英

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



Hello

I am trying to make a reusable component in blazor server

A list box, where I pass an id (which it used to populate itself, and then what the user selects is passed back

My idea is to pass an ID to a component, from a parent to child, which works fine, but I can only get a string back from the child and I would like to send a class object back, is it possible, I have tried the below




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>

Yes it is possible. You can add Parameter like this

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

Then after the button that deletes clicked, you create the item type of Mymodel and send it back to parent

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

In parent page you have to create function that gets the child data.

private void GetDeletedInfo(Mymodel model){}

The call of component will be

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

@Baskovli @Quango need help here, I'm creating a user control to import csv file using csvHelper, in my case MyModel will be always different how I can achieve it? any help will be appriciated

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

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