ViewComponent with optional parameters

Viewed 4676

I am creating a set of View Components that represent filters on different views. They work great so far, but I don't understand this behavior I am experiencing.

If I use declare two InvokeAsync:

public async Task<IViewComponentResult> InvokeAsync(string name)
public async Task<IViewComponentResult> InvokeAsync(string name, string title)

Then I get this:

Error: View component 'MyViewComponent' must have exactly one public method named 'InvokeAsync' or 'Invoke'.

But if I do something like this instead:

public async Task<IViewComponentResult> InvokeAsync(string name, string title = "")

Then this happens:

<vc:my name="Hello" title="Hello"></vc:my> // Gets rendered
<vc:my name="Hello" title=""></vc:my>  // Gets rendered
<vc:my name="Hello"></vc:my> // Doesn't call InvokeAsync

So, is it possible at all to use default parameters? I cannot use a Model for this (client requirements)

2 Answers

From other comments it sounds like this might be fixed in .NET 6, but if you need a solution now, a simple one is to create an options container class and pass the parameters in that.

public class MyComponentOptions
{
    public string Name;
    public string Title;
}

Your Invoke method takes the options:

public async Task<IViewComponentResult> InvokeAsync(MyComponentOptions options)

In your HTML you can pass them like this:

@{ var bob = new MyComponentOptions { Name = "Bob" }; }
<vc:my-component options="@bob" />

@{ var alice = new MyComponentOptions { Name = "Alice", Title = "Developer" }; }
<vc:my-component options="@alice" />

^-- Both of these work.

Related