【发布时间】:2015-12-11 12:30:15
【问题描述】:
我有一个 ASP.NET MVC 项目。
HomeController.cs
public class HomeController : Controller
{
private siteDBEntities db = new siteDBEntities();
// GET: Main/Home
public ActionResult Index()
{
return View();
}
public PartialViewResult _theLastPost()
{
var a = (from c in db.Posts
orderby c.ID_Post descending
select new { c.Title,c.Content});
return PartialView(a.ToList());
}
}
索引.cshtml
@model IEnumerable<test1.Models.Post>
@{
ViewBag.Title = "Tourism";
Layout = "~/Areas/Main/Views/Shared/_Layout.cshtml";
}
@Html.Partial("_theLastPost")
部分视图_theLastPost.cshtml
@model IEnumerable<test1.Models.Post>
@foreach (var item in Model)
{
<h2>
@item.Title
</h2>
<p>
@item.Content
</p>
}
Post.cs 这是我的视图模型,我只想从 EF6 框架中获取标题和内容。
public partial class Post
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Post()
{
this.Comments = new HashSet<Comment>();
this.Keywords = new HashSet<Keyword>();
}
public int ID_Post { get; set; }
public int ID_Category { get; set; }
public int ID_Writer { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public string Url { get; set; }
public Nullable<System.TimeSpan> Time { get; set; }
public Nullable<System.DateTime> Date { get; set; }
public string Index_Image { get; set; }
public virtual Category Category { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Comment> Comments { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Keyword> Keywords { get; set; }
public virtual Writer Writer { get; set; }
}
我想显示最后一篇文章,但它显示了这个错误
The model item passed into the dictionary is of type 'test1.Models.Post', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[test1.Models.Post]
更新 1: 该错误已通过使用
修复@{ Html.RenderAction("_theLastPost"); }
现在我有这个错误: 无法在 LINQ to Entities 查询中构造实体或复杂类型“siteDB.Post”。
已修复: 我只是为部分视图(_theLastPost)编辑控制器,如下所示:
public PartialViewResult _theLastPost()
{
var a = (from c in db.Posts
orderby c.ID_Post descending
select c);
return PartialView(a);
}
【问题讨论】:
-
试试@model IEnumerable
-
如果你的意思是在局部视图中,我之前添加了它
-
TBH:提供的代码与提供的错误不匹配。你改变了什么吗?看起来您的视图模型不是 IEnumerable 或您的 @Html.Partial 调用与所述不符
-
如您所见,模型已传递给局部视图是 IEnumerable @freedomn-m