繁体   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