I used the following tutorial to help me build an RSS Reader in my ASP.NET MVC3 Razor application:
However, unlike the tutorial example, I want the RSS feed to be displayed on every page, and have therefore added it to my layout file, /Views/Shared/_Layout.cshtml
I currently only have 2 views on my site, and to get the RSS Reader to work on both views I’ve got the following code in my HomeController:
public class HomeController : Controller
{
//
// GET: /Index/
public ActionResult Index()
{
return View(CT.Models.RssReader.GetRssFeed());
}
public ActionResult About()
{
return View(CT.Models.RssReader.GetRssFeed());
}
}
From my WebForms experience, I would simply add the RSS Reader code in my master page code behind, and it would automatically work on every page.
Is there a Controller for layout pages which allows me to do the same?
How can I get this to work on every call of the layout page, without having to return anything?
EDIT: Following @Sebastian’s advice, I’ve now added this code to a Partial View, removed CT.Models.RssReader.GetRssFeed() from return View() and included this in my layout file:
@Html.Partial("_MyPartialView")
The code in this partial view is:
<ul>
@foreach (var item in Model)
{
<li>
<a href="@item.Link" target="_blank">@item.Title</a>
</li>
}
</ul>
However, I’m not getting a runtime error:
Object reference not set to an instance of an object.
It’s erroring on the line @foreach (var item in Model)
You have to create a partial view and add functionality there.
Then in your layout, render this partial.
EDIT
Is your partial view really a partial view? The reason I said that is because you have “_” in front of the name which suggests that it might be a layout (might just be a naming convention).
To fix object reference error, you have to add the @Model declaration on top of your partial view.
Hope it helps.
UPDATE
In order to use different model in partial view, you need to explicitly declare which model you are going to use on render partialmethod.
Let me know if that resolved your issue.