Mike Pateras
Mike Pateras

Reputation: 15015

MVC: How can I pass a list from one view to another?

I've got some data in a view that I would like to pass to a child partial view. Part of that data is a list of dates that I would like to display in the partial view. I'm pretty sure I can't pass an IEnumerable from one view to another (when I try list is null in the controller). Assuming that is the case, is there a good work around?

I've thought about just concatenating the values into a string and then just parsing that string in the controller. That seems a bit hackish, but I think it would work. Is there a problem with doing it like that? Is there a better way?

It just seems like such a shame to have to re-fetch the data that I've got in the parent view. I'm hoping there's another way to do it.

Update: This is the model for the partial view:

public class SiteVisitDetailModel
{
    public String URL
    {
        get;
        set;
    }

    public List<DateTime> Dates
    {
        get;
        set;
    }
}

And this is the code from the parent view to add the partial view:

<% Html.Telerik().PanelBar().Name("PanelBar").HtmlAttributes(new { style = "padding-left: 0em;" }).Items(items =>
{
    foreach (var item in Model.Visits)
    {
        SiteVisitDetailModel model = new SiteVisitDetailModel();
        model.URL = item.Key;
        model.Dates = (from siteVisit in item
                             select siteVisit.Time).ToList();

        items.Add()
            .Text(item.Key.ToString() + " " + item.Count().ToString() + " visits")
            .LoadContentFrom("SiteViewDetail", "Report", model);        

    }
}).Render();

In the SiteVisitDetail action method, model.URL is properly set, and model.Dates is null.

Upvotes: 0

Views: 2048

Answers (2)

griegs
griegs

Reputation: 22760

Check this post out on how to pass models around.

Essentially you shoiuld probably pass a model to the view that contains your list. then you can extend it later on.

Multiple models sent to a single view instance

Upvotes: 1

Terje
Terje

Reputation: 1763

If I understood your problem correctly...

If your partial view can be strongly typed, its model could be the list, and you can do:

<%Html.RenderPartial("PartialView",myList);%>

Otherwise, the parent view can add the list to its ViewData, which would be accessible from the partial view.

Upvotes: 4

Related Questions