MrK*_*shi 32 c# asp.net-core-mvc asp.net-core
查看组件:
public class WidgetViewComponent : ViewComponent
{
private readonly IWidgetService _WidgetService;
private WidgetViewComponent(IWidgetService widgetService)
{
_WidgetService = widgetService;
}
public async Task<IViewComponentResult> InvokeAsync(int widgetId)
{
var widget = await _WidgetService.GetWidgetById(widgetId);
return View(widget);
}
}
Run Code Online (Sandbox Code Playgroud)
在视图〜/ Views/Employees/Details.cshtml中
@await Component.InvokeAsync("Widget", new { WidgetId = Model.WidgetId } )
Run Code Online (Sandbox Code Playgroud)
视图组件位于〜Views/Shared/Components/Widget/Default.cshtml
我收到的错误如下:
InvalidOperationException:无法找到类型为"MyApp.ViewComponents.WidgetViewComponent"的合适构造函数.确保类型具体,并为公共构造函数的所有参数注册服务.
Joe*_*tte 92
问题是你的构造函数是私有的:
private WidgetViewComponent(IWidgetService widgetService)
{
_WidgetService = widgetService;
}
Run Code Online (Sandbox Code Playgroud)
它应该是公开的,否则DI无法访问它:
public WidgetViewComponent(IWidgetService widgetService)
{
_WidgetService = widgetService;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16303 次 |
| 最近记录: |