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

查看:75
本文介绍了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的子类)。您可以使用控制器的视图方法返回的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是要传递的,因此,在目前情况下,我们认为数据的类型派生的(在列表.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有您指定的类型参数T中的ViewPage,所以在我们的例子this.ViewData.Model一直类型列表中的类型。

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。

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天全站免登陆