femi
femi

Reputation: 984

how do you pass in a collection to an MVC 2 partial view?

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?

Upvotes: 2

Views: 1047

Answers (3)

Robert Harvey
Robert Harvey

Reputation: 180958

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.

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532765

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>>" %>

Upvotes: 0

spender
spender

Reputation: 120548

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

Upvotes: 0

Related Questions