1

基本上我的職位表的帖子:如何顯示按月asp.net的MVC

public partial class Mak 
{ 
    public string Name{ get; set; }   
    public DateTime writingDate{ get; set; } 
} 

我想列出職位爲每個對我的看法分組個月。
我的代碼:

@foreach (var tar in Model.Mak.OrderByDescending(x=> x.writingDate.Month).Select(x=> x.writingDate)) 
{ 
    <a href="/m/[email protected]&[email protected]">@tar.ToString("MMMM yyyy")</a> 

    @foreach (var mak in Model.Mak.Where(x=> x.writingDate==tar)) 
    { 
     <a href="/m/@mak.Name"></a><div> @mak.Name</div> 
    } 

} 

輸出:

July 2017 
Connected //post name 

    July 2017 
Linq to SQL 

    July 2017 
OOP 

    July 2017 
Linq Querys 

所需的輸出:

June 2017 
xyz //post name 
abc  
    July 2017 
Connected 
Linq to SQL 
OOP 
Linq Querys 

我應該怎麼寫這個查詢?

回答

0

集團通過月份和年份,然後依次通過分組的項目您的收藏。

@{ 
    var posts = Model.Mak; // Assuming this is the list of posts; 
    DateTimeFormatInfo dtfi = new DateTimeFormatInfo(); 
    var postGrouped = posts.GroupBy(x => new { Month = x.WritingDate.Month, 
                 Year = x.WritingDate.Year }); 
} 
@foreach (var item in postGrouped) 
{ 
    <a href="@Url.Action("date","m",new { year=item.Key.Year, month=item.Key.Month})"> 
         @dtfi.GetAbbreviatedMonthName(item.Key.Month) @item.Key.Year</a> 
    foreach (var post in item) 
    { 
     <div> 
      <a href="/m/@(post.Title)">@post.Title</a> 
     </div> 
    } 
} 

GetAbbreviatedMonthName方法採用表示月份的整數並返回字符串名稱。

我還建議使用html helper方法來呈現鏈接的href值(使用Url.ActionHtml.ActionLink輔助方法)。在編寫C#類時,請考慮遵循PascalCasing方法。 (WritingDate而不是writingDate

+0

感謝您的意見兄弟,讓我問一個問題,爲什麼我應該遵循PascalCasing方法? – Anil

+0

你不需要。但這就是這個行業所做的。看看微軟做什麼https://github.com/dotnet/docs/blob/master/docs/csharp/programming-guide/inside-a-program/coding-conventions.md – Shyju

+0

謝謝你,我看這些約定 – Anil

0

你可以嘗試這樣的事情:

@{ 
    // gets the records grouped based on Year and Month. 
    // Creates an object of IEnumerable<IGrouping<>> type 
    var groupedByMonth = Model.Mak 
         .OrderByDescending(x => x.writingDate) 
         .GroupBy(x => new { x.writingDate.Year, x.writingDate.Month }); 

    // loop thorugh each group 
    foreach (var group in groupedByMonth) 
    { 
     // each group will have 2 "Keys" with Month and Year value. 
     // or use Url.Action() to form your anchor 
     <a href="/m/[email protected]&[email protected]">@group.FirstOrDefault().writingDate.ToString("MMMM yyyy")</a> <br> 

     // looping through contents of group 
     // IGrouping inherits from IEnumerable, so this is possible 
     foreach (var mak in group) 
     { 
      <a href="/m/@mak.Name"><div> @mak.Name</div> </a><br> 
     } 
    } 
} 
+0

感謝,它的工作 – Anil