I have a Blazor Page with one View, but I want to use two ViewModels for that, depends on which URL I use.
@page "/canSimStatic"
@page "/CanSimDynamic"
@using System.Diagnostics;
@using edge_cantraficSimulator.Data
@using edge_cantraficSimulator.ViewModels
@using System.Threading;
@using System.IO;
@using Microsoft.AspNetCore.Mvc.Rendering;
@inject NavigationManager NavigationManager
@if (NavigationManager.Uri.Contains("canSimStatic"))
{
@inject ViewModels.CanSimStaicViewModell viewmodel
}
@if (NavigationManager.Uri.Contains("CanSimDynamic"))
{
@inject ViewModels.CanSimDynamicViewModdels viewmodel
}
My problem is, no matter which of these both URLs I use, it always choses the second one as viewmodel
2
Answers
I checked this with output the URl to the page:
both show "Secound Option from …/CanSimDynamic". So Blazor seem to handel both internally with the same Uri. So I would recommend to use a url parameter for this:
you can use the url e.g. in NavMenu like:
@inject
is Razor code and is like a directive. You can’t use it in logic loops like you have done.You need to load both and then select which one you want to use. You can do something like this:
Whether you use object or say
ICanSimViewModell
depends on how you’re using it. I would suggest defining an interface that both "models" conform to and thenbecomes: