简体   繁体   English

如何在ASP.NET Core MVC中的ViewComponent中传递4个以上的参数

[英]How to pass more than 4 parameters in a ViewComponent in ASP.NET Core MVC

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. 我有一个ViewComponent,我需要将超过4个值传递给ViewComponent,但是当我尝试时,它会给我下面的错误。

Error CS0746 Invalid anonymous type member declarator. 错误CS0746无效的匿名类型成员声明符。 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 调用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. 我将使用TagHelper传递数据,有没有办法将模型传递给ViewComponent,我已经尝试但参数始终为null。

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. 编译器错误本身与ViewComponents或4个参数无关:问题是匿名类型中的"2" ,这是无效的。 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 . D = Model.D - 隐式地在匿名类型上创建名称D

However, the next parameter is "2 ", without a name and no implicit creation of a property. 但是,下一个参数是"2 ”,没有名称,也没有隐式创建属性。 If you want this last parameter to compile, you'll need to give it a name of its own, eg: 如果你想要编译这个最后一个参数,你需要给它一个自己的名字,例如:

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. 我应该提到你需要匿名类型属性的名称来匹配你的InvokeAsync函数中声明的InvokeAsync ,这意味着你需要将filter更改为B才能使该部分工作。 Todd Skelton's answer offers a safer approach to handling that, however. 然而,Todd Skelton的回答提供了一种更安全的处理方法。

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" })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM