Allen Buckley's Blog

September 2010 Entries

Passing conditional data to a Partial View in MVC

 

It was a bit painful trying to figure out in ASP.NET MVC how to pass conditional data to a Partial View without the data being loaded in the View page every time it loaded.  Obviously looking back it looks extremely simple, but I thought I would post some sample code in case someone else runs into this issue.

The following is the code from the View page.  It simply checks for a authenticated user so that the List<NewsModel> object only gets loaded in that scenario.  There is no reason to load the model if the user is not logged in and this is why I extracted the load to the RenderAction helper.


    <% if (Request.IsAuthenticated) {
        Html.RenderAction("NewsFeed"); } %>

 

 

The RenderAction calls the ActionResult NewsFeed from the Page View’s Controller class.  Inside this method I simply loaded the List<NewsModel> and then passed it to the User Control via the PartialView call.

public ActionResult NewsFeed()
{
    List<NewsModel> newsModelList = DataRepository.LoadList();

    return PartialView("NewsFeed", newsModelList);
}

 

 

Below is the NewsFeed User Control.  You have to set up the Model that is being passed in the Inherits Page Directive.  After that you can access the list using the Model variable.  In this case I simply loop through the Model using a foreach loop and display the NewsHeadline string.  That’s all there is to it.  Now you have your data being loaded conditionally and not every time the View page loads.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.
Collections.Generic.List<Website.Models.NewsModel>>" %>
<% foreach (Website.Models.NewsModel newsModel in Model) 
{ %>
    <%= newsModel.NewsHeadline %> 
<br />
<%;}%>