简体   繁体   中英

Blazor application passing variables from razor page to c#

I'm still new to Blazor and c#

I'm struggling to pass a variable (row ID selected by user) in the razor page and use that variable as a parameter in a SQL query to filter and populate a list/table on a different razor page.

Originally I just used a static variable and just set it each time a user selected a row, however this causes problems when more than one user interacts with the system.

What's the best way to handle this? Do I need to use some sort of session variable?

In the simplest form, you can do it as follows:

@page "/Customers/{CustomerId:guid}"
...
...
@code {
   [Parameter]
   public Guid CustomerId { get; set; }
}

But if you have a table, you'd better check this link

I believe that thanks to this, you can do your work faster and without errors. Also, the code will be easier to read and maintain. Because at the end of the day you will have a code that fits a certain template like this:

<DataGrid TItem="Employee"
        Data="@employeeList"
        ReadData="@OnReadData"
        TotalItems="@totalEmployees">
    <DataGridCommandColumn TItem="Employee" />
    <DataGridColumn TItem="Employee" Field="@nameof(Employee.Id)" Caption="#" Sortable="false" />
    <DataGridColumn TItem="Employee" Field="@nameof(Employee.FirstName)" Caption="First Name" Editable="true" />
    <DataGridColumn TItem="Employee" Field="@nameof(Employee.LastName)" Caption="Last Name" Editable="true" />
    <DataGridColumn TItem="Employee" Field="@nameof(Employee.EMail)" Caption="EMail" Editable="true" />
    <DataGridColumn TItem="Employee" Field="@nameof(Employee.City)" Caption="City" Editable="true" />
    <DataGridColumn TItem="Employee" Field="@nameof(Employee.Zip)" Caption="Zip" Editable="true" />
    <DataGridNumericColumn TItem="Employee" Field="@nameof(Employee.Childrens)" Caption="Childrens" Editable="true" />
    <DataGridColumn TItem="Employee" Field="@nameof(Employee.Salary)" Caption="Salary" Editable="true">
        <DisplayTemplate>
            @($"{( context as Employee )?.Salary} €")
        </DisplayTemplate>
        <EditTemplate>
            <NumericEdit TValue="decimal" Value="@((decimal)(((CellEditContext)context).CellValue))" ValueChanged="@(v=>((CellEditContext)context).CellValue=v)" />
        </EditTemplate>
    </DataGridColumn>
</DataGrid>

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