Vi100
Vi100

Reputation: 4203

Navigate from @ondblclick event handler in Blazor (Server-Side) composing route dynamically

I'm trying to navigate from a @ondblclick handler on a element on Server Side Blazor, trying to open a detail page for each row. This is the relevant code:

@inject NavigationManager nm
...
@for (var elem in elements)
{
    <tr @ondblclick="@(() => nm.NavigateTo("Cuenta/" + elem.Id.ToString()))">
    ...
    </tr>
}

but I'm always getting this exception:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot implicitly convert type 'void' to 'object''

I've also tryed this ways:

<tr @ondblclick="@(() => nm.NavigateTo("Cuenta/" + @elem.Id.ToString()))">
<tr @ondblclick="nm.NavigateTo("Cuenta/" + elem.Id.ToString())">
<tr @ondblclick="@(nm.NavigateTo("Cuenta/" + elem.Id.ToString())">
<tr ondblclick="@(() => nm.NavigateTo("Cuenta/" + elem.Id.ToString()))">

and probably others, but none seems to be correct, but extrangely if I do the following it works (but it's not usable=:

 <tr @ondblclick="@(() => nm.NavigateTo("Cuenta/123"))">

So, how can I use navigation manager to navigate directly from the template?

Edit: It seems it has something to do with "elem" being a dynamic object, since elements is a List of dynamics...

Upvotes: 0

Views: 950

Answers (1)

David Masterson
David Masterson

Reputation: 1005

I think you need to instantiate a new instance of the elem.Id.ToString() inside the for loop something like

@inject NavigationManager nm
...
@for (var elem in elements)
{
    string tmpString  = elem.Id.ToString();
    <tr @ondblclick="@(() => nm.NavigateTo("Cuenta/" + tmpString))">
    ...
    </tr>
}

Hope this helps.

This is a standard C# behavior, not related to Blazor, where the lambda expression @(() => DoSomething(i)) has access to a variable and not to its value. You've got to define a variable which is local to your loop.

Upvotes: 2

Related Questions