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)
By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.
The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.
A view component class: Supports constructor dependency injection. Doesn't take part in the controller lifecycle, therefore filters can't be used in a view component.
The thing with optional parameters is, they are BAD because they are unintuitive - meaning they do NOT behave the way you would expect it. Here's why: They break ABI compatibility ! so you can change the default-arguments at one place.
According to this Github issue, it doesn't seem like it will be done by the team.
@rynowak Apr 29, 2017 - I'm going to move it in and mark it up for grabs. At this point locking down our public APIs and completing the tooling story needs to take priority.
Update 4 years later: This was finally accepted for .NET 6 and this should now work!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With