Aspnetcore: Ability to pass parameters to event handlers

Created on 26 Aug 2018  路  4Comments  路  Source: dotnet/aspnetcore

It seems that currently parameters are not supported. If you do e.g. this:

    @foreach(var x in xCollection)
    {
        <li>x.Name <a onclick="@HandleClick(x.Value)">Click me</a></li>
    }

    //More code

    @functions {
        private void HandleClick(string p)
        {           
        }
    }

you get a compilation error:

error CS1503: Argument 1: cannot convert from 'void' to 'string'

It would simplify the binding to be able to pass parameters there.

area-blazor

Most helpful comment

The syntax is

    @foreach(var x in xCollection)
    {
        <li>x.Name <a onclick="@(() => HandleClick(x.Value))">Click me</a></li>
    }

    //More code

    @functions {
        private void HandleClick(string p)
        {           
        }
    }

All 4 comments

The syntax is

    @foreach(var x in xCollection)
    {
        <li>x.Name <a onclick="@(() => HandleClick(x.Value))">Click me</a></li>
    }

    //More code

    @functions {
        private void HandleClick(string p)
        {           
        }
    }

@Suchiman, is onclick="@(() => HandleClick(x.Value))" a temporary solution or the way to go in Blazor ?

@enetstudio it's the way to go, this is standard C# and razor, @() defines an expression context and inside what we've got is a normal capturing lambda expression that takes no arguments and calls another method () => HandleClick(x.Value) like is often used in LINQ. onclick is just something that takes an Action, Action<UIEventArgs> or Func<Task>.

Ok, thanks. I feel this should be reflected in the docs - it's not immediately obvious. Will send a pull request.

Was this page helpful?
0 / 5 - 0 ratings