[英]creation of view with dynamic Model in asp.net mvc
I am new Asp.Net Mvc . 我是新的Asp.Net Mvc 。 I am doing a sample application for Blogging .
我正在为Blogging做一个示例应用程序。 I tried to create Partial view for Archives for categorizing Post according to date .
我尝试为Archives创建部分视图 ,以便根据日期对Post进行分类。
Month/Year(count)
Post 1
Post 2
Month/Year(count)
Post 1
Post 2
In Controller 在控制器中
[ChildActionOnly]
public ActionResult Archives()
{
var post = from p in db.Posts
group p by new { Month =p.Date.Month, Year = p.Date.Year } into d
select new { Month = d.Key.Month , Year = d.Key.Year , count = d.Key.Count(), PostList = d};
return PartialView(post);
}
Please help me write View for this Action with this Month, Year , Count and collection of Post . 请帮我写这个动作的视图与本月,年,计数和邮政集合。
You may be struggling because you are passing an anonymous type into your View. 您可能正在努力,因为您将匿名类型传递到您的视图中。 I would create a
ViewModel
to represent your type; 我会创建一个
ViewModel
来表示你的类型;
public class Archive
{
public string Month { get; set; }
public string Year { get; set; }
public int Count { get; set; }
public ICollection<Post> Posts { get; set; }
}
and then change your action to use the type; 然后更改您的操作以使用该类型;
[ChildActionOnly]
public ActionResult Archives()
{
var post = from p in db.Posts
group p by new { Month =p.Date.Month, Year = p.Date.Year } into d
select new Archive { Month = d.Key.Month , Year = d.Key.Year, Count = d.Key.Count(),
PostList = d };
return PartialView(post);
}
and then you can strongly type your view to the Archive
class; 然后你可以强烈地将你的视图输入到
Archive
类;
@model IEnumerable<Archive>
@foreach (Archive archive in Model)
{
<h2>
@archive.Month / @archive.Year
</h2>
}
Let me know if I can be of further assistance. 如果我能得到进一步的帮助,请告诉我。
Matt 马特
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.