我对 ASP.Net MVC 还很陌生。我创建了一个填充 List<> 的模型具有多个称为“结果”的自定义对象。然后,在我的控制器中,我获取此列表并将其放入 ViewData 中。
在我看来,我对如何利用这个列表(aspx 页面)有点不知所措。我的第一次尝试只是将 ViewData["Results"] 放在 <% %> 之间,但显然这不起作用,我怀疑我需要以某种方式对其进行转换,并引用我对 Result 自定义对象的原始定义。然而,aspx 页面似乎并没有真正为这种类型的编码设置......并且没有代码隐藏,而且我听说我应该保持视图“哑”。我见过的大多数示例似乎都没有涵盖传递自定义对象的场景,只是简单的字符串等。
是否可以仅使用 <% %> 来优雅地完成此操作?句法?我是否需要创建一个代码隐藏页面并在那里处理它?如果是这样,将如何创建一个,因为默认情况下不提供它们。
I'm pretty new to ASP.Net MVC. I've created a model that fills a List<> with multiple custom objects called "Result". Then, in my controller, I get this List and put it into the ViewData.
I am at a bit of a loss as to how to utilize this List in my view (aspx page). My first try was just to put ViewData["Results"] between the <% %>, but clearly this is not working, and I suspect I need to cast it somehow and also reference my original definition of the Result custom object. However, the aspx page does not really seem set-up for this type of coding...and there is no code-behind, and I've heard I'm supposed to keep the view "dumb". Most of the examples I've seen don't seem to cover this scenario of passing custom objects, just simple strings, etc.
Can this be done elegantly using just the <% %> syntax? Do I need to create a code-behind page and handle it there? If so, how would one be created, as they are not provided by default.
发布评论
评论(1)
为了使视图与您从操作传递给它的对象无缝集成,您需要更改位于顶部的
@Page 指令
中的Inherits=
属性的视图。确保通过以下方式将此对象从操作传递到视图:
在本例中,您有一个名为
Result
的自定义对象,您将其列表传递到视图。因此,在@Page
指令中,您将Inherits=
更改为因此,完整的
@Page
指令将如下所示:它的作用是告诉
Model
类型为List
的View
。现在,在视图中,
Model
对象将自动转换为List
类型,以便您可以无缝、干净地执行以下操作。To make the view integrate seamlessly with the object you're passing to it from the action, you need to change the
Inherits=
attribute in the@Page directive
located at the top of the view.Make sure you pass this object to the view from the action, via the following:
In this case, you have a custom object called
Result
which you pass a list of to the view. So in the@Page
directive you change theInherits=
toSo your full
@Page
directive will look something like this:What this does is tell the
View
that yourModel
is of typeList<MyNameSpace.Models.Result>
.Now, in the view, the
Model
object will be automatically cast to typeList<MyNameSpace.Models.Result>
so you can do the following seamlessly and cleanly.