MVC 5中如何输出含指定话题标签的IEnumerable<TwitterStatus>集合?
在Razor视图中展示Twitter推文集合
没问题,我来帮你搞定在视图里展示这些Twitter推文的事儿!假设你用的是ASP.NET MVC的Razor视图(.cshtml文件),可以参考下面的代码来实现:
@{ ViewBag.Title = "#test话题推文展示"; } <h2>带有#test标签的推文</h2> @* 先判断是否有数据,避免空引用错误 *@ @if (ViewBag.Tweets != null && ViewBag.Tweets.Any()) { <div class="tweets-list"> @foreach (var tweet in ViewBag.Tweets) { <div class="tweet-item"> <div class="tweet-author"> <strong>@tweet.User.ScreenName</strong> </div> <div class="tweet-content"> @tweet.Text </div> <div class="tweet-meta"> <small>发布时间: @tweet.CreatedAt.ToString("yyyy-MM-dd HH:mm:ss")</small> <span>转发数: @tweet.RetweetCount</span> <span>点赞数: @tweet.FavoriteCount</span> </div> </div> <hr /> } </div> } else { <p>暂时没有找到带有#test标签的推文哦~</p> }
代码说明:
- 首先做了空值判断:先检查
ViewBag.Tweets是否不为空且包含数据,防止出现空引用异常 - 遍历每个
TwitterStatus对象,取出常用的属性展示:tweet.User.ScreenName:推文作者的用户名tweet.Text:推文的具体内容tweet.CreatedAt:推文的发布时间(这里格式化了显示格式)tweet.RetweetCount和tweet.FavoriteCount:分别是转发数和点赞数
- 你可以根据自己的需求调整展示的字段,或者添加CSS样式来美化推文的展示效果
内容的提问来源于stack exchange,提问作者betamech
相关产品推荐
相关产品推荐

