As a follow-up to this post, I needed to get the home-made Twitter feed onto the layout page of our MVC 4 app. Like this:
tkglaser.apphb.com/TwitterLayout
The problem is that the layout page has no model and no code-behind. Since the Twitter feed is populated in code-behind on the server, this is a problem.
The answer is a PartialView populated by a ChildAction.
The Model remains unchanged from the original implementation.
Change the Action that retrieves the tweets and populates the model to be a ChildAction returning a PartialView.
[ChildActionOnly]
public PartialViewResult Tweets()
{
RestClient client = new RestClient("http://api.twitter.com/1");
// [...] see original post for full implementation
model.Tweets =
jsonDeserializer.Deserialize<List<Tweet>>(response);
return PartialView(model);
}
For the View, create a new partial view displaying the tweets.
@model net.tkglaser.demos.Models.TwitterFeed.LandingModel
<ul>
@foreach (var tweet in Model.Tweets)
{
<li>
<img src="@tweet.user.profile_image_url" />
@Html.Raw(tweet.GetTextWithLinks())
</li>
}
</ul>
Now, you can simply insert the tweets into the layout, or anywhere else using this line:
@Html.Action("Tweets")
This enables you to put your Twitter feed into the layout so every page will display it.
As always, please feel free to leave a comment if you find this useful or have a suggestion.