【发布时间】:2015-07-15 12:52:58
【问题描述】:
我是 MVC 新手,需要一些帮助。我创建了一个名为 SideBarController 的控制器、一个名为 SideBarViewModel 的视图模型和一个名为 SideBar 的视图。我想在我的 _Layout.cshtml 文件中使用 SideBar,这样它就可以在我的所有页面上使用。
我收到此错误消息:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Learn2MVC.Models.BlogPosts]', but this dictionary requires a model item of type 'Learn2MVC.Models.SideBarViewModel'.
我的 SideBarViewModel 如下所示:
使用 System.Collections.Generic;
namespace Learn2MVC.Models
{
public class SideBarViewModel
{
public IEnumerable<BlogCategories> Categories { get; set; }
public IEnumerable<BlogPosts> LatestPosts { get; set; }
}
}
它在里面保存了 BlogCategories 和 BlogPosts,这是另外两个只能 get;set; 的类。属性。
SideBarController 看起来像这样:
public ActionResult SideBar()
{
var model = new SideBarViewModel();
model.Categories = GetCategories();
model.LatestPosts = LatestPosts();
return View(model);
}
//Method for getting the categories
public IEnumerable<BlogCategories> GetCategories()
{
var categoryList = new List<BlogCategories>();
using (var connection = new DatabaseClass().ConnectToDatabase())
using (OleDbCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT * FROM Categories ORDER BY CategoryName ASC";
OleDbDataReader reader = command.ExecuteReader();
while (reader.HasRows && reader.Read())
{
categoryList.Add(new BlogCategories()
{
Id = reader.GetInt32(0),
Name = reader.GetString(1)
});
}
if (!reader.HasRows)
categoryList.Add(new BlogCategories(){ Id = -1,Name = "Inga kategorier hittades"});
return categoryList;
}
}
LatestPosts 的工作方式与 GetCategories 基本相同。 SideBar.cshtml 中的重要代码如下所示:
@model Learn2MVC.Models.SideBarViewModel
@foreach (var category in Model.Categories)
{
<li><a href="#">@category.Name</a></li>
<li>@category.Id</li>
}
@foreach (var post in Model.LatestPosts)
{
<li><a href="#">@post.Title</a></li>
}
在我的 _Layout.cshtml 中,我尝试使用包含 SideBar
@{ Html.RenderPartial("../SideBar/SideBar"); }
但是,它不起作用。 除了当我去 localhost/SideBar/SideBar - 然后循环工作得很好,没有错误消息弹出。但是,当我转到我的索引页面时,我收到了错误消息。不知道哪里出了问题,大家能帮帮我吗?
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-4 razor asp.net-mvc-5