C# MVC将项目列表返回到视图
谁能帮帮我吗。我试图从数据库中检索存储详细信息列表,并在视图中简单地显示该列表 存储模式:C# MVC将项目列表返回到视图,c#,asp.net-mvc,C#,Asp.net Mvc,谁能帮帮我吗。我试图从数据库中检索存储详细信息列表,并在视图中简单地显示该列表 存储模式: public class StorageModel { [Required] [Display(Name = "Storage Name")] public string Name { get; set; } [Required] [Display(Name = "Date From")] public string DateFrom { get; se
public class StorageModel
{
[Required]
[Display(Name = "Storage Name")]
public string Name { get; set; }
[Required]
[Display(Name = "Date From")]
public string DateFrom { get; set; }
[Required]
[Display(Name = "Date To")]
public string DateTo { get; set; }
[Required]
[Display(Name = "Size")]
public string Size { get; set; }
}
控制器方法:
public ActionResult ViewStorage()
{
List<CommonLayer.TblNewsStorage> storageList = new BusinessLayer.Storage().getAllStorage().ToList();
return View(storageList);
}
我得到以下错误:
传递到字典中的模型项的类型为“System.Collections.Generic.List1[CommonLayer.TblNewsStorage]”,但此字典需要类型为“System.Collections.Generic.IEnumerable
1[NewsLibrary.Models.StorageModel]”的模型项
@model IEnumerable
必须传入相同的数据类型
你要进来了
List<CommonLayer.TblNewsStorage>
列表
如果仔细查看视图希望看到的模型,您会发现它是NewsLibrary.Models.StorageModel的IEnumerable。您正在传递CommonLayer.TblNewsStorage类型的列表/IEnumerable。确保这两个数据类型相同。@foreach(模型中的变量项){
项目名称
}
像这样试试。您需要将@html.displayfor(model=>item.name)删除为标记中的item.name什么不起作用?运行时会发生什么?请粘贴错误dump@Shoe对不起,我忘记粘贴错误。用error更新错误错误是不言自明的。您正在传递CommonLayer.TblNewsStorage的列表,但您的视图采用NewsLibrary.Models.StorageModel的模型。确保两者使用相同的型号。不,DisplayName实际上位于外部。该函数返回显示名(如果没有DisplayName属性,则称为变量名)。模型基于CommonLayer.TblNewsStorage类型(直接从数据库检索),我可以进行某种转换吗?使用automapper之类的工具进行自动映射。我应该在将它们传递到视图之前在控制器中进行转换,或者为视图创建一个特殊的ViewModel:)。
@model IEnumerable<NewsLibrary.Models.StorageModel>
@{
ViewBag.Title = "ViewStorage";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>ViewStorage</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.DateFrom)
</th>
<th>
@Html.DisplayNameFor(model => model.DateTo)
</th>
<th>
@Html.DisplayNameFor(model => model.Size)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateFrom)
</td>
<td>
@Html.DisplayFor(modelItem => item.DateTo)
</td>
<td>
@Html.DisplayFor(modelItem => item.Size)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
@model IEnumerable<NewsLibrary.Models.StorageModel>
List<CommonLayer.TblNewsStorage>