ASP.NET MVC:如何将列表(从模型中的类)传递给视图中的中继器? [英] ASP.NET MVC: How do I pass a list (from a class in Model) to a repeater in a View?

查看:17
本文介绍了ASP.NET MVC:如何将列表(从模型中的类)传递给视图中的中继器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何做到以上几点?我已经开始使用 MVC,但在传递数据时遇到了问题.

How do I do the above? I've started using MVC and I'm having issues passing data around.

我的具体问题是处理模型中的对象列表,我需要在视图中访问这些对象并进行迭代.

My specific problem is to do with a list of objects I have in my Model which I need to access in a View and iterate through.

提前致谢.

推荐答案

假设您的控制器操作看起来像

Let's say your controller action looks something like

public ActionResult List()
{
    List<string> myList = database.GetListOfStrings();
    (...)
}

现在要将列表传递给视图,请说List.aspx".您可以通过让操作返回 ViewResult(ViewResult 是 ActionResult 的子类)来实现此目的.您可以使用控制器的 View 方法返回一个 ViewResult,如下所示:

Now you want to pass your list to the view, say "List.aspx". You do this by having the action return a ViewResult (ViewResult is a subclass of ActionResult). You can use the Controller's View method to return a ViewResult like so:

public ActionResult List()
{
    List<string> myList = database.GetListOfStrings();
    (...)
    return View("List", myList);
}

为了能够在您的视图中以强类型方式访问列表,它必须派生自 ViewPage,其中 T 是您传入的数据类型.因此,在当前情况下,我们的视图(在 List.aspx.cs) 会是这样的:

To be able to access the list in a strongly-typed fashion in your view, it must derive from ViewPage, where T is the type of the data you are passing in. Thus, in the current case our view (in List.aspx.cs) would something like this:

public partial class List : ViewPage<string>
{
    (...)
}

以这种方式传入视图的数据称为ViewData".要访问数据,您必须通过 ViewPage 上的 ViewData.Model 属性.因此,要呈现您将编写的列表内容(在 List.aspx 中)

The data passed into the view in this way is referred to as the "ViewData". To access the data, you must go through the ViewData.Model properties on the ViewPage. Thus, to render the contents of the list you would write (in List.aspx)

<ul>
    <% foreach(var s in this.ViewData.Model){ %>
    <li> <%= s %> </li>
    <% } %>
</ul>

此处,this.ViewData.Model 具有您在 ViewPage 中指定的类型参数 T 的类型,因此在我们的示例中 this.ViewData.Model 具有类型 List.

Here, this.ViewData.Model has the type you specified the type parameter T in ViewPage, so in our case this.ViewData.Model has type List.

可以使用转发器来渲染这样的东西,但我不推荐它.如果您想使用类似的东西,请查看 CodePlex 上 MvcContrib 项目的 Grid 模块.

You can use a repeater for rendering stuff like this, but I wouldn't recommend it. If you want to use something similar, check out the Grid module of the MvcContrib project on CodePlex.

这篇关于ASP.NET MVC:如何将列表(从模型中的类)传递给视图中的中继器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆