简体   繁体   English

带有使用MVC 1.0的控制器的ASP.Net MVC ViewUserControl

[英]ASP.Net MVC ViewUserControl with controller using MVC 1.0

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. 由于所有预览版本和一个正式版本中有关mvc的所有信息之间都存在混淆,因此我非常困惑如何处理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. 因此,我在Views \\ Shared文件夹中放置了一个新的ViewUserControl(ListEvents.ascx)。

I am requesting this ListEvents.ascx to render on my Home/Index view like this: 我要求将此ListEvents.ascx呈现在我的“主页/索引”视图上,如下所示:

<p>
    Here's a list of events:
    <% Html.RenderPartial("ListEvents");%>
</p>

How would I go about passing my model to this viewusercontrol? 我将如何将模型传递给此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. 我什至无法传递任何验证状态,因此无法传递null参数。 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! 因此,另一种选择是将该数据存储到ViewData []成员中,但我的viewusercontrol不应依赖于其父项的ViewData!

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. 一个简单的答案 :viewusercontrol应该始终从其所在的View接收其模型。 Working around this, like by adding a codebehind file to a viewusercontrol, would break the MVC pattern. 解决此问题的方法(例如,将代码隐藏文件添加到viewusercontrol中)将破坏MVC模式。

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. 如果要为RenderPartial每个实例提供模型,则情况可能类似于在博客应用程序中呈现多个条目。 You could fetch each model from a collection in your page model and pass it to the user control like this: 您可以从页面模型中的集合中获取每个模型,并将其传递给用户控件,如下所示:

foreach (var post in Model.Entries) {
  Html.RenderPartial("PostTemplate", post);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM