Nicolas Lewentorp
Nicolas Lewentorp

Reputation: 119

I need to pass a parameter from Parent to Child

Ok, so I have a schedule page that I access using the URL localhost/{RoomId} where {RoomId} for now is an int (1, 2, 3 etc.) so this is the first line of this page:

@page "/roomzfront/{RoomId:int}"

This works to get the corresponding data from the database, but the actual booking function is placed in a child component and when I try to pass this parameter using:

    @functions { int PresentRoom = RoomId; }

I get the error 'a field initializer cannot reference the non-static field...'

However, using the code (Parent):

@functions { int PresentRoom = 1; }

and this code (Child):

    [CascadingParameter(Name="PresentRoomId")] protected int PresentRoom { get; set; }

doesn't pass the value anyway. ( Got the tip here:)

Upvotes: 0

Views: 719

Answers (2)

Nicolas Lewentorp
Nicolas Lewentorp

Reputation: 119

Data binding solved my problem. A good explanation is found here Data binding

In Parent:

<Child.Component TRoomId="RoomId"></Child.Component>

@code {
private int RoomId{ get; set; };

}

In Child:

<div>Room Id from Room: @TRoomId</div>

@code{
[Parameter] public int TRoomId {get; set;}

}

Upvotes: 0

Stanley
Stanley

Reputation: 36

Try saving the room ID in the page model (@Model) then you can easily access the room ID in the page using e.g. @Model.RoomId

Have a look at the following link: https://chsakell.com/2013/05/02/4-basic-ways-to-pass-data-from-controller-to-view-in-asp-net-mvc/

Upvotes: 1

Related Questions