views:

91

answers:

3

hello ,

how do you pass in a collection to an MVC 2 partial view? I saw an example where they used the syntax;

<% Html.RenderPartial("QuestionPartial", question); %>

this passes in only ONE question object..

what if i want to pass in several questions into the partial view and , say, i want to list them out...how would i pass in SEVERAL questions?

thanks

A: 

Because your partial view will usually be placed in some other (main) view, you should strongly-type your main view to a composite ViewData object that looks something like this:

public class MyViewData
{
    public string Interviewee { get; set }
    // Other fields here...
    public Question[] questions { get; set }
}

In your controller:

var viewData = new MyViewData;
// Populate viewData object with data here.

return View(myViewData);

and in your view:

<% Html.RenderPartial("QuestionPartial", Model.questions); %>

Then use tvanfosson's advice on the partial view.

Robert Harvey
More info on strongly-typed view models here: http://nerddinnerbook.s3.amazonaws.com/Part6.htm
Robert Harvey
A: 

Instead of passing question, why not pass a collection of questions, for instance List<QuestionType>?

spender
A: 

Normally, you'd have an IEnumerable<Question> as a property in your view model -- in reality it might be a list or an array of Question objects. To use it in your partial, just pass that property of the view model as the model to the partial. The partial should be strongly typed to accept an IEnumerable<Question> as it's model.

 <% Html.RenderPartial("QuestionPartial", Model.Questions ); %>

Partial:

<%@ Page Language="C#"
         MasterPageFile="~/Views/Shared/Site.Master"
         Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Question>>" %>
tvanfosson