簡體   English   中英

在asp.net mvc中使用動態模型創建視圖

[英]creation of view with dynamic Model in asp.net mvc

我是新的Asp.Net Mvc 我正在為Blogging做一個示例應用程序。 我嘗試為Archives創建部分視圖 ,以便根據日期Post進行分類。

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

請幫我寫這個動作的視圖與本月,年,計數和郵政集合。

您可能正在努力,因為您將匿名類型傳遞到您的視圖中。 我會創建一個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>
}

如果我能得到進一步的幫助,請告訴我。

馬特

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM