Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewComponent with optional parameters

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)

like image 999
Camilo Terevinto Avatar asked May 26 '17 19:05

Camilo Terevinto


People also ask

How do you pass optional parameters?

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.

Can parameters be optional?

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.

Can we inject dependency in ViewComponent?

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.

Should we use optional parameter?

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.


1 Answers

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!

like image 123
Camilo Terevinto Avatar answered Sep 22 '22 18:09

Camilo Terevinto