[英]Getting constructor error in ASP.NET Core MVC web app?
I keep getting the error below when trying to pass my IEnumerable
to the view.尝试将
IEnumerable
传递给视图时,我不断收到以下错误。
I'm really puzzled in what is it, the return type of GetCandidates
is IEnumerable<Candidate>
.我真的很困惑它是什么,
GetCandidates
的返回类型是IEnumerable<Candidate>
。
InvalidOperationException: A suitable constructor for type 'System.Collections.Generic.ICollection`1[Models.Candidate]' could not be located.
InvalidOperationException:找不到适合类型“System.Collections.Generic.ICollection`1[Models.Candidate]”的构造函数。 Ensure the type is concrete and all parameters of a public constructor are either registered as services or passed as arguments.
确保类型是具体的,并且公共构造函数的所有参数要么注册为服务,要么作为参数传递。 Also ensure no extraneous arguments are provided.
还要确保没有提供无关的参数。
My Candidate
model class:我的
Candidate
模型类:
public class Candidate
{
public Guid candidateId { get; set; }
public string fullName { get; set; }
public bool seen { get;set; }
public bool status { get; set; }
public IEnumerable<Experience> experience { get; set; }
}
My registered services:我注册的服务:
builder.Services.AddHttpClient();
builder.Services.AddTransient<IApiService, ApiService>();
// other code //
My Index.cshtml
view:我的
Index.cshtml
视图:
@page
@using Models
@model ICollection<Candidate>
@{
ViewData["Title"] = "Home page";
}
//other code//
You need firstly learn how to get started in Razor Pages:您首先需要了解如何开始使用 Razor Pages:
https://docs.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-6.0&tabs=visual-studio#razor-pages https://docs.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-6.0&tabs=visual-studio#razor-pages
Razor Pages do not use @model ModelName
,it uses @model <PageName>Model
,which is different from MVC. Razor Pages 不使用
@model ModelName
,它使用@model <PageName>Model
,这与 MVC 不同。
Change your Index.cshtml
like below:更改您的
Index.cshtml
如下所示:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
@foreach(var item in Model.Candidate)
{
@item.fullName
}
The Index.cshtml.cs
like below: Index.cshtml.cs
如下所示:
public class IndexModel : PageModel
{
public List<Candidate> Candidate { get; set; }
public void OnGet()
{
//for easy testing, I just hard-coded...
Candidate = new List<Candidate>()
{
new Candidate(){fullName="aa"},
new Candidate(){fullName="aa1"},
new Candidate(){fullName="aa2"}
};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.