ASP.Net MVC ViewUserControl 与使用 MVC 1.0 的控制器
由于所有预览版本和一个正式版本中有关 mvc 的所有信息之间存在混淆,我对如何处理 viewusercontrols 感到非常困惑。 因此,一劳永逸地告诉我如何实现这个示例:
我有一个即将发生的事件列表,需要在我的网站的几个页面上显示。 因此,我在 Views\Shared 文件夹中放置了一个新的 ViewUserControl (ListEvents.ascx)。
我请求此 ListEvents.ascx 在我的 Home/Index 视图上呈现,如下所示:
<p>
Here's a list of events:
<% Html.RenderPartial("ListEvents");%>
</p>
如何将我的模型传递给此 viewusercontrol? 我知道我可以做到这一点:
<p>
Here's a list of events:
<% Html.RenderPartial("ListEvents", (new Model.Services.EventService(null)).ListEvents());%>
</p>
但这似乎不是一件非常聪明的事情,从视图内部创建一个新模型?! 还是我这里错了? 我什至无法传递任何验证状态,因此参数为空。 因此,另一种选择是将此数据存储到 ViewData[] 成员中,但我的 viewusercontrol 不应依赖于其父级的 ViewData!
我确信对此有一个非常简单的答案,请分享,因为我已经浏览完这个问题的网页。
谢谢!
简单答案: viewusercontrol 应始终从其所在的视图接收其模型。 解决这个问题(例如向 viewusercontrol 添加代码隐藏文件)会破坏 MVC 模式。
Because of the confusion between all the info that is out there about mvc from all the preview releases and the one official release I am very confused how to deal with viewusercontrols.
So once and for all, tell me how to implement this example:
I have a list of upcoming events that needs to be displayed on several pages of my website. Therefore I have put a new ViewUserControl (ListEvents.ascx) inside my Views\Shared folder.
I am requesting this ListEvents.ascx to render on my Home/Index view like this:
<p>
Here's a list of events:
<% Html.RenderPartial("ListEvents");%>
</p>
How would I go about passing my model to this viewusercontrol? I know I can do this:
<p>
Here's a list of events:
<% Html.RenderPartial("ListEvents", (new Model.Services.EventService(null)).ListEvents());%>
</p>
But that doesn't seem like a very smart thing to do, creating a new model from inside a view?! Or am I wrong here? I can't even pass any validationstate, hence the null parameter.
So an alternative option is to store this data into the ViewData[] member, but my viewusercontrol is not supposed to be dependant on the ViewData of it's parent!
I'm sure there is a very simple answer to this, please share as I'm done browsing the web for this problem.
Thanks!
Simple Answer:
A viewusercontrol should always receive it's model from the View in which it resides. Working around this, like by adding a codebehind file to a viewusercontrol, would break the MVC pattern.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,将使用与页面相同的模型。 如果您想为
RenderPartial
的每个实例提供一个模型,您的情况可能就像在博客应用程序中渲染多个条目。 您可以从页面模型中的集合中获取每个模型并将其传递给用户控件,如下所示:By default, the same model as the page will be used. If you want to provide a model to each instance of
RenderPartial
, your situation is probably like rendering several entries in a blog application. You could fetch each model from a collection in your page model and pass it to the user control like this: