[英]Asp.Net MVC Cast Model in view
我有三个模型:动物,狗和猫。
动物类
public class Animal
{
}
班犬
public class Dog : Animal
{
}
和班猫
public class Dog : Animal
{
}
还有两个控制器(DogController 和 CatController),在每个控制器中,都有一个索引动作,返回视图以显示列表结果。
狗控制器
public class DogController : Controller
{
public DogController ()
{
}
public async Task<IActionResult> Index()
{
DogRepository IRepos = new DogRepository ();
// Get List of Dogs
IList<Animal> listDogs= await IRepos.GetListDogs();
return View(ilIst);
}
[Httpost]
public async Task<IActionResult> Add(Animal Dog)
{
....
// Add dog to Database
return RedirectToAction("Index");
}
}
狗的索引视图
@model IEnumerable<Dog>
@{
ViewData["Title"] = "Index";
}
<div class="row">
<div class="table-responsive">
<table class="table">
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Dog_ID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Dog_Name)
</td>
</tr>
}
</table>
</div>
</div>
在Dog Controller的索引Action中,返回类型为IList<Animal>
,索引视图中的模型类型为IEnumerable<Dog>
。 执行应用程序时,会产生错误
处理请求时发生未处理的异常。 InvalidOperationException:传入 ViewDataDictionary 的模型项的类型为“System.Collections.Generic.List 1[Animal]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable
1[Dog]” 1[Animal]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable
。
因此,将控制器中动作发送的动物列表转换为视图中模型的狗类型列表非常重要。 我们如何将动物列表转换为视图中的狗列表,@model IEnumerable 作为 IEnumerable 不起作用。
post动作中同样的事情,我们如何在动作中将Dog模型从视图转换为Animal模型
多态性似乎不适用于页面模型。 可以为猫和狗定义局部视图,局部视图使用子类,主视图使用基类作为模型。
主视图(索引):
@model IEnumerable<Animal>
@{
ViewData["Title"] = "Index";
}
<div class="row">
<div class="table-responsive">
<table class="table">
<thead>
</thead>
<tbody>
@foreach (var item in Model)
{
@if (item is Dog)
{
<partial name="_DogPartial" model="item" />
}
}
</table>
</div>
</div>
部分视图(_DogPartial):
@model Dog
<tr>
<td>
@Html.DisplayFor(modelItem => Model.Dog_ID)
</td>
<td>
@Html.DisplayFor(modelItem => Model.Dog_Name)
</td>
</tr>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.