ASP.NET MVC 2:foreach、RenderPartial、ViewModel
我正在尝试采用一种我发现的看起来很干净的技术。
以前,我的 Partial 内部有循环。我正在循环遍历 Partial 中的模式...但后来我遇到了一个示例,其中 foreach
循环存在于主页中,而 Partial 只是循环的核心。
他们是这样完成的:
<% int index = 1; // iteration
foreach (var item in Model.Deal) { %>
<% Html.RenderPartial("DealList", item, new ViewDataDictionary {{ "index", index }}); %>
<% i++; // increase the interation
} %>
但在我的示例中,我使用的是 ViewModel,现在我处于部分状态,我无法像以前那样访问“项目”。相反,我唯一的选择是 Model.Deal ...
如果我无法通过说 来访问它,那么使用
?请注意,View 和 Partial 都强类型化为同一个 ViewDataModel。RenderParial
帮助器传递“item”有什么意义呢? item.StoreName
I'm trying to employ a technique that I came across that seems quite clean.
Previously, my Partial had the loop inside of it. I was looping through the mode within the Partial... but then I came across an example where the foreach
loop existed in the main page, while the partial was just the meat of the loop.
They accomplished it like so:
<% int index = 1; // iteration
foreach (var item in Model.Deal) { %>
<% Html.RenderPartial("DealList", item, new ViewDataDictionary {{ "index", index }}); %>
<% i++; // increase the interation
} %>
But in my example, I'm using a ViewModel, and now that I'm in the partial, I can't access "item" like I used to be able to. Instead my only option is Model.Deal
...
What is the point of passsing "item" with the RenderParial
helper if I can't access it by saying item.StoreName
? Note, both the View and the Partial are strongly typed to the same ViewDataModel.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在部分“DealList”内部,您的模型将是主视图中的任何
item
。在分部视图内部,Model.Deal
引用item
内部的Deal
对象(来自主视图)。这意味着您的
StoreName
属性将可以在部分视图中作为Model.StoreName
进行访问。作为旁注,我组合了一个扩展方法来处理多个部分视图的渲染,以便不需要循环。
新方法称为 RenderPartials :
使用此方法,您可以简单地说:
在主视图内,没有循环。
还有更多 关于此的信息在这里,其中解释了有关 htmlFormat 参数等的更多信息。
希望这对您有帮助。
Inside of the partial "DealList" your model will be whatever
item
is in the main view. Inside of the partial view,Model.Deal
refers to aDeal
object inside ofitem
(from the main view).This means that your
StoreName
property will be accessible asModel.StoreName
within your partial view.As a side note, I put together an extension method to deal with rendering of multiple partial views so as to not require the looping.
The new method is called
RenderPartials
:Using this method you can simple say:
inside your main view, without the loop.
There's some more information about this here which explains more about the htmlFormat parameter etc.
Hope this is helpful to you.