Search code examples
c#asp.net-coreasp.net-core-viewcomponent

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)


Solution

  • 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!