![](/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.