I have a ASP.NET MVC Project .
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());
}
}
Index.cshtml
@model IEnumerable<test1.Models.Post>
@{
ViewBag.Title = "Tourism";
Layout = "~/Areas/Main/Views/Shared/_Layout.cshtml";
}
@Html.Partial("_theLastPost")
PartialView _theLastPost.cshtml
@model IEnumerable<test1.Models.Post>
@foreach (var item in Model)
{
<h2>
@item.Title
</h2>
<p>
@item.Content
</p>
}
Post.cs this is my view model , that i just want get title and content from EF6 framework .
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; }
}
I want show the last post , but it show me this error
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]
Update 1: That error has fixed by using
@{ Html.RenderAction("_theLastPost"); }
Now i have this error : The entity or complex type 'siteDB.Post' cannot be constructed in a LINQ to Entities query.
Fixed: I just edit Controller for partial view(_theLastPost) like below:
public PartialViewResult _theLastPost()
{
var a = (from c in db.Posts
orderby c.ID_Post descending
select c);
return PartialView(a);
}