This is a Blazor Server introduction project.
It shows the following points:
- Routing
- Components
- Bindings
- Events
- Methods
- Create project Blazor Server App
- Start project to check if it works
- Add a Navlink into NavMenu.razor (copy and replace href, oi-icon and Name)
<div class="nav-item px-3">
<NavLink class="nav-link" href="calc">
<span class="oi oi-calculator" aria-hidden="true"></span> CO2 Output Calc
</NavLink>
</div>
- Create Calc.razor Page in Pages
- Add Page Routing
@page "/calc"
- Show result
- Add PageTitle Component
<PageTitle>CO2 Output Calc</PageTitle>
- Change
<h3>
text to CO2 output - Create field Kilometres
private int Kilometres = 100;
- Add label and input
<label>Kilometres</label>
<input type="number" @bind="Kilometres"/>
- Create record Transportation
public record Transportation(string? Title, double Co2PerKmInGramm);
- Create List of Transportation and instance values
private List<Transportation> Transportations = new()
{
new ("Car 🚗", 147),
new ("Airplane 🛫", 230),
new ("Train 🚝", 32)
};
- Add foreach loop below input without variables
@foreach (var t in Transportations)
{
<div class="card w-25 mt-2">
<div class="card-body">
<h2 class="card-title"></h2>
<hr />
<p class="card-text fw-bold"> kilograms</p>
</div>
</div>
}
- Add Title to h5
@t.Title
- Add Method to calculate
private double CalculateCo2InKg(double co2value) => (co2value * Kilometres) / 1000;
- Add Method to card p class
@CalculateCo2InKg(t.Co2PerKmInGramm)
- Add
@bind:event="oninput"
to input.
@code {
int Kilometres = 100;
List<Transportation> Transportations = new List<Transportation>()
{
new Transportation{Title = "Car 🚗", Co2PerKmInGramm = 147 },
new Transportation{Title = "Airplane 🛫", Co2PerKmInGramm = 230 },
new Transportation{Title = "Train 🚄", Co2PerKmInGramm = 32 }
};
class Transportation
{
public required string Title { get; set; }
public required double Co2PerKmInGramm { get; set; }
}
double CalculateCo2InKg(double co2value)
{
return (co2value * Kilometres) / 1000;
}
}