Dotvvm:路由参数获取 Context 的空异常

Dotvvm: Route paramets get null exception for Context

每次我在我的视图模型中得到 Context 的空异常:

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

在 dotvvmStartup.cs 我有这个代码:

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

当我点击 index.dothml 中的路线 link 时:

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

所以我得到了 Context 的 NullReferenceException,我还检查了 Locals Context,我看到 Context 的值为 null。拜托,你知道我错过了什么吗?

顺便说一句,我也尝试修改 dotvvmStartup.cs 中的代码,如下所示,但我得到了相同的结果,但 Context:

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

您似乎正在尝试访问尚未提供的构造函数中的 Context 属性。

目前,推荐的方法是覆盖Init方法并读取该方法中的参数值。

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; }