如何解决Web 浏览器上的表格未填充 foreach循环问题?
问题:我希望我的数据库中的宠物显示在网络浏览器上。我的 foreach 没有出现错误,但宠物没有出现。
怀疑:我确定这与我如何在 HomeController 中创建新列表、将其传递到索引中的部分、然后在 _PetListView 中使用 @model List 的方式有关.
请求:你能帮我理解我遗漏了什么吗?
Pet.cs
namespace petShelter.Models
{
public class Pet
{
[Key]
public int PetId { get; set; }
[required]
public string Name { get; set; }
[required]
public string Type { get; set; }
[required]
public string Description { get; set; }
public string Skill1 { get; set; }
public string Skill2 { get; set; }
public string Skill3 { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public Owner Owner { get; set; }
public int? OwnerId { get; set; }
}
}
HomeController.cs
[HttpGet("/")]
public IActionResult Index()
{
List<Pet> allPets = new List<Pet>();
return View("Index",allPets);
}
Index.cshtml
@{
List<Pet> newPet = new List<Pet>();
Owner newOwner = new Owner();
}
<div>
<div>
<partial name="_PetListView" model="newPet" />
<partial name="_OwnerListView" model="newOwner" />
</div>
</div>
_PetListView.cshtml
@model List<Pet>
<div class="text-center">
<div>
<header>
<h1>Pet Shelter</h1>
<h4>These pets are looking for a good home!</h4>
<a href="Pet">Add a new pet to the shelter</a>
</header>
</div>
<div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach (Pet animal in Model)
{
<tr>
<td><a asp-controller="Home" asp-action="Pet"></a></td>
<td>@animal.Name Name</td>
<td>@animal.Type Type</td>
<td>@animal.Description Description</td>
</tr>
}
</tbody>
</table>
</div>
</div>
解决方法
您正在传递空列表。你必须用宠物和主人填满它们。
首先创建一个viewModel
public class PetViewModel
{
public List<Pet> Pets {get; set;};
public List <Owner> Owners {get; set;};
}
填完之后
[HttpGet("/")]
public IActionResult Index()
{
var model = new PetViewModel
{
Pets= ...your code to create a list of pets,Owners = ...the code to create a list of owhers
}
return View("Index",model);
}
并修复视图
Index.cshtml
@model PetViewModel
<div>
<div id="pets">
<partial name= "_PetListView" model= "@Model.Pets" />
</div>
<div id="owners">
<partial name ="_OwnerListView" model= "@Model.Owners" />
</div>
</div>
更新
对于测试你可以试试这个:
var model = new PetViewModel
{
Pets= new List<Pet>{ new Pet {Name="PetName",Type="PetType",Description="PetDesctription"} },Owners = new List<Owner> { new Owner{ FirstName="FirstName",LastName="LastName"}}
}
或者如果您已经拥有 EF
var model = new PetViewModel
{
Pets= _context.Pets.ToList(),Owners = _context.Owners.ToList()
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。