'how to bind List<model> to create view in ASP.NET Core MVC
I am trying to create a form to collect the qualifications of students. At first, the list should contain 4 objects for four different qualifications. segment of the create view
@for (var i = 0; i < 4; i++)
{
<div class="col-md-3 me-2">
<label asp-for="@Model[i].Institute" class="control-label col-md"></label>
<input asp-for="@Model[i].Institute" class="form-control" />
<span asp-validation-for="@Model[i].Institute" class="text-danger"></span>
</div>
<div class="col-md-3 me-2">
<label asp-for="@Model[i].YearGraduated" class="control-label"></label>
<input asp-for="@Model[i].YearGraduated" class="form-control" />
<span asp-validation-for="@Model[i].YearGraduated" class="text-danger"></span>
</div>
}
<div class="form-group d-flex-row m-auto mt-2">
<input type="submit" name="submit" value="Save and Continue"/>
</div>
This is my controller:
public IActionResult Create()
{
var model = new List<Qualification>();
model = _context.Qualifications.ToList();
return View(model);
}
And this is the model class:
public partial class Qualification
{
public Qualification()
{
Subjects = new HashSet<Subject>();
}
public int Id { get; set; }
public int StudentId { get; set; }
public string Institute { get; set; } = null!;
public short YearGraduated { get; set; }
public virtual Student Student { get; set; } = null!;
public virtual ICollection<Subject> Subjects { get; set;
}
My problem is when I run the code, nothing is generated and no error at all.
Can anyone help?
Solution 1:[1]
Here you missing in your code.
@model List<Qualification> // declare on top of the file
@if(Model !=null){
for (var i = 0; i < Model.Count; i++)
{
<div class="col-md-3 me-2">
<label asp-for="@Model[i].Institute" class="control-label col-md"></label>
<input asp-for="@Model[i].Institute" class="form-control" />
<span asp-validation-for="@Model[i].Institute" class="text-danger"></span>
</div>
<div class="col-md-3 me-2">
<label asp-for="@Model[i].YearGraduated" class="control-label"></label>
<input asp-for="@Model[i].YearGraduated" class="form-control" />
<span asp-validation-for="@Model[i].YearGraduated" class="text-danger"></span>
</div>
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ajay Gupta |
