2014-01-22 59 views
0

我是新的Asp.Net Mvc。我正在做一個示例應用程序博客。我試圖創建局部視圖對於檔案進行分類郵政根據日期在asp.net中使用動態模型創建視圖mvc

Month/Year(count) 
    Post 1 
    Post 2 
Month/Year(count) 
    Post 1 
    Post 2 

在控制器

[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); 
    } 

請幫我寫查看該行動與此月,年,計數和郵政的集合。

+0

@downvote是我的問題錯了? – arun

回答

2

您可能會因爲將匿名類型傳遞給您的視圖而苦苦掙扎。我會創建一個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; } 
} 

然後改變你的動作使用類型;

[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); 
} 

然後您可以強烈地將您的視圖鍵入Archive類;

@model IEnumerable<Archive> 

@foreach (Archive archive in Model) 
{ 
    <h2> 
    @archive.Month/@archive.Year 
    </h2> 
} 

讓我知道如果我可以得到進一步的幫助。

馬特

相關問題