3

I have a ViewComponent and I need to pass more than 4 values to the ViewComponent, but when I try, it's giving me the error below.

Error CS0746 Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

Code looks like this.

public async Task<IViewComponentResult> InvokeAsync(
    string A, string B, string C, string D, string E)
{

}

Calling the ViewComponent

@await Component.InvokeAsync(
    "ViewComponent2",
    new { A = Model.A, filter = "B", C = Model.C, Model.D, "2" })

I will use TagHelper to pass the data and is there any way to pass a model to the ViewComponent, I have tried but the parameter is always null.

0

2 Answers 2

4

The compiler error itself has nothing to do with either ViewComponents or 4 parameters: The problem is the "2" in your anonymous type, which is invalid. The anonymous type you're creating has these first four parameters:

  • A = Model.A
  • filter = "B"
  • C = Model.C
  • D = Model.D - The name D is created here on the anonymous type implicitly.

However, the next parameter is "2", without a name and no implicit creation of a property. If you want this last parameter to compile, you'll need to give it a name of its own, e.g.:

new { A = Model.A, filter = "B", C = Model.C, Model.D, E = "2" }

EDIT

I should've mentioned that you'll need the names of the anonymous type's properties to match up with those declared in your InvokeAsync function, which means you'll need to change filter to B in order for that part to work. Todd Skelton's answer offers a safer approach to handling that, however.

Sign up to request clarification or add additional context in comments.

Comments

3

You can use classes to ensure your models are correct to avoid anonymous type errors.

public class InvokeRequest
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
    public string D { get; set; }
    public string E { get; set; }
}

public async Task<IViewComponentResult> InvokeAsync(InvokeRequest request)
{
    //...
}

@await Component.InvokeAsync("ViewComponent2", new InvokeRequest(){ A = Model.A, B = "B", C = Model.C, D = Model.D, E = "2" })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.