如何将集合传递给 MVC 2 部分视图?

发布于 2024-08-31 07:14:31 字数 215 浏览 8 评论 0原文

如何将集合传递给 MVC 2 部分视图? 我看到了一个他们使用语法的例子;

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

这仅传递一个问题对象。

如果我想将几个问题传递到部分视图中,并且我想将它们列出来,该怎么办?

我该如何通过几个问题?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

樱花细雨 2024-09-07 07:14:31

因为您的部分视图通常会放置在其他(主)视图中,所以您应该将主视图强类型化为复合 ViewData 对象,如下所示:

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

在您的控制器中:

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

return View(myViewData);

在您的视图中:

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

然后使用 tvanfosson 的建议关于局部视图。

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.

南…巷孤猫 2024-09-07 07:14:31

为什么不传递问题集合,例如 List,而不是传递问题

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

唯憾梦倾城 2024-09-07 07:14:31

通常,您的视图模型中会有一个 IEnumerable 作为属性 - 实际上它可能是 Question 对象的列表或数组。要在局部中使用它,只需将视图模型的属性作为模型传递给局部。部分应该是强类型的,以接受 IEnumerable 作为其模型。

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

部分的:

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

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>>" %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文