![](/img/trans.png)
[英]model item passed into the dictionary is of type 'System.Collections.Generic.List, but this dictionary requires a model item of type
[英]Dictionary requires a model item of type System.Collections.Generic.List
我有一个layout.csthml,其中包含一个侧边栏,还包含一个@Renderbody。 @Renderbody和侧边栏在其各自的视图中均使用以下内容。
@model List<appstowindows.Models.apps>
@foreach (var item in Model){...}
两种视图都可以很好地显示列表,但是当我尝试在视图中打开编辑URL时,仍然出现错误:
传递到字典中的模型项的类型为System.Data.Entity.DynamicProxies,字典需要类型为System.Collections.Generic.List的模型项
编辑网址
@Html.ActionLink("Edit", "Edit", new { id = item.app_key })
指数
public ActionResult Index()
{
var applist = db.apps.Include(a => a.appgroups);
applist = db.apps.Include(a => a.appstatus);
return View(applist.ToList());
}
编辑
public ActionResult Edit(int? id)
{
apps apps = db.apps.Find(id);
return View(apps);
}
重要说明:如果我要删除其中一个视图中的任一列表,则编辑URL可以正常工作。
是什么导致此错误以及如何解决?
更新:
@model myproject.Models.apps
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm("Edit", "Apps", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>apps</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.app_key)
</div>
}
您正在将错误类型的模型传递给视图。 传递的对象的类型为System.Data.Entity.DynamicProxies
而System.Collections.Generic.List
是必需的。 检查提供哪个对象作为其参数。
更新:问题出在您的布局页面上指定的model
。 Edit
视图基于布局页面,因此它需要List<apps>
类型的模型才能呈现。 但是“ Edit
视图”要求apps
在相反的一侧作为模型。 虽然没有类型,即List<apps>
和apps
同时存在,但是您的代码将无法工作。
通常,应避免键入布局页面,因为基于该布局的所有视图都将需要相同或后代的模型类型。 如果您的所有页面都应该真正共享一些信息,则可以使用多种选项解决此问题:
async
(有一些技巧可以使它们async
,但事实并非如此) async
的。 同样,这些块不会延迟页面加载,并且可以用微调框或类似方式装饰。 在您的情况下,错误是由@model List<appstowindows.Models.apps>
引起的。 执行“ Edit
视图时,它首先呈现布局页面标记,因此不适合作为模型提供给“ Edit
视图的类型为apps
对象。 我想,您在布局中指定了一种类型,因为在所有页面之间共享了一些标记(如果我错了,只需从布局中删除@model
,一切都会好起来的),并且这种共享可以由一个人实现我之前提出的方法
如果您选择第二个,则应该向控制器添加一个动作(不知道您要渲染什么信息,因此我将其称为Foo
)
public ActionResult Foo()
{
/*get data for your shared content part*/
return PartialView(/*provide data here*/);
}
然后为其创建带有标记的View
,应将其共享。 (来自您布局的那一个,会引起问题)
@model List<appstowindows.Models.apps>
@foreach (var item in Model){...}
然后从您的布局中删除该标记,然后调用@ Html.Action(“ Foo”) 。
顺便说一句,我想您应该学习有关ASP.MVC中的布局页面和模型的一些信息,官方网站是一个很好的起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.