Search code examples
c#dotvvm

Dotvvm: Route paramets get null exception for Context


Everytime I get null exception for Context in my viewmodel:

 var TestId = Convert.ToInt32(Context.Parameters["Id"]);

In dotvvmStartup.cs I have this code:

config.RouteTable.Add("Default", "", "Views/index.dothtml");   
config.RouteTable.Add("TestPage", "testpage/{Id?}", "Views/testpage.dothtml");

When I click on route link in index.dothml:

<dot:RouteLink RouteName="TestPage" Text="Go!" Param-Id="1" />

So I got NullReferenceException for Context also I checked in Locals Context and I saw that Context had value null. Please, do you know what I missed?

By the way I also try modify code in dotvvmStartup.cs like you can see below but I got same result with null exception for Context:

config.RouteTable.Add("Default", "", "Views/index.dothtml", null);   
    config.RouteTable.Add("TestPage", "testpage/{Id?}", "Views/testpage.dothtml", new { Id = 2 });

Solution

  • It seems that you are trying to access the Context property in the constructor where it's not available yet.

    For now, the recommended way is to override the Init method and read the parameter values inside this method.

    public override Task Init() 
    {
        TestId = Convert.ToInt32(Context.Parameters["Id"]);
        return base.Init();
    }
    

    In the upcoming 1.1 release of DotVVM, we'll have parameter binding where you can just declare a property in the viewmodel and use an attribute to bind it to the parameter in route or query string, like this:

    [FromRoute("Id")]
    public int TestId { get; set; }