PartialView used by 2 views accessing ViewModel data from each

62 views Asked by At

I have 2 viewmodels each of them have a property called RSSFeed of type RSS. I have 2 views (one for each viewmodel) and I want them to share the same partialview which renders the data in RSSFeed.

In my main views, I have:

@{ Html.RenderPartial("Social", new ViewDataDictionary(Model)); }

In my Social partiavlview I wanted to use something like:

@ViewBag.RSSFeeds.Feed[0].Title

Running that give me 'Cannot perform runtime binding on a null reference'

Each ViewModel has:

public RSS RSSFeed = new RSS();

The supporting classes are:

public class RSSItem
{
    public string Title { get; set; }
    public string Link { get; set; }
    public string Description { get; set; }
    public DateTime PubDate { get; set; }
}
public class RSS
{
    public string FeedURL { get; set; }
    public List<RSSItem> Feed = new  List<RSSItem>();

}

Any help is greatly appreciated. I wonder if I am actually able to do what I am looking to do or have completely done this the wrong way.

2

There are 2 answers

2
McGaz On

In your example above, .Feed is an empty List of RSSItems. Your code:

@ViewBag.RSSFeeds.Feed[0].Title

If attempting to get the title from the first Feed in your (empty) list which is why you are getting the null reference error.

You'd need to do a check in your partial to make sure that a Feed exists before using it.

@if (ViewBag.RSSFeeds != null && ViewBag.RSSFeeds.Feed.Count() > 0)

If you use the ViewBag, you'll need to populate that on every page load that uses it - if it's only 2 pages that might not be a problem. Maybe it would be better to use the Session to store your RSSFeeds instead?

Set

 Session["RSSFeeds"] = RSSFeeds;

Get

if (Session["RSSFeeds"] != null)
    return (RSSFeeds)Session["RSSFeeds"];
else
    return null;
3
laskdjf On

I can't comment yet, but are the inputs you are using for RenderPartial correct? on MSDN there is no method that takes a ViewDataDictionary and one other object.