skip to Main Content

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


  1. I checked this with output the URl to the page:

    @if (NavigationManager.Uri.Contains("canSimStatic"))
    {
       <p>First Option from @NavigationManager.Uri</p>
    }
    else if (NavigationManager.Uri.Contains("CanSimDynamic"))
    {
        <p>Secound Option from @NavigationManager.Uri</p>
    }
    

    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:

    @page "/canSim/{Option}"
    @inject NavigationManager NavigationManager
    
    @if (NavigationManager.Uri.Contains("Dynamic"))
    {
        <p>First Option from Url  @NavigationManager.Uri - Option @Option</p>
    }
    else if (NavigationManager.Uri.Contains("Static"))
    {
        <p>Secound Option from Url  @NavigationManager.Uri - Option @Option</p>
    }
    
    @code {
        [Parameter]
        public String Option { get; set; }
        
        //...
    }
    

    you can use the url e.g. in NavMenu like:

    <NavLink class="nav-link" href="canSim/Dynamic">
       <span class="oi oi-plus" aria-hidden="true"></span> Counter
    </NavLink>
    
    Login or Signup to reply.
  2. @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:

    @code
    {
    [Inject] private ViewModels.CanSimStaicViewModell viewModelStatic {get; set;}
    [Inject] private ViewModels.CanSimDynamicViewModdels viewModelDynamic {get; set;}
    
    private object viewModel;
    
    protected override void OnInitialized() {
       if (NavigationManager.Uri.Contains("Dynamic"))
          viewModal = viewModelDynamic;
       else
          viewModal = viewModelStatic;
    }
    

    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 then

    private object viewModel;
    

    becomes:

    private ICanSimViewModell viewModel;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search