您如何在 asp.net mvc 中使用显示“孤岛"的用户控件?数据的? [英] How do you use usercontrols in asp.net mvc that display an "island" of data?

查看:21
本文介绍了您如何在 asp.net mvc 中使用显示“孤岛"的用户控件?数据的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出如何在 asp.net mvc 中使用用户控件.我知道如何将用户控件添加到视图以及如何将数据传递给它.我无法弄清楚的是,您如何在不必检索和传递每个控制器中的数据的情况下做到这一点?

I am trying to find out how to use usercontrols in asp.net mvc. I know how to add a usercontrol to a view and how to pass data to it. What I haven't been able to figure out is how do you do this without having to retrieve and pass the data in every single controller?

例如,如果我有一个用户控件,它显示站点中几个但不是所有页面上的最新帖子,我如何编写控制器以便获取该用户控件的数据并将其传递给用户控件仅从网站中的一个位置获取和传递数据,而不是在使用用户控件的每个不同控制器中获取和传递数据?

For example, if I have a user control that displays the most recent posts on several but not all the pages in the site, how do I write the Controllers so that I get data for that usercontrol and pass it to the user control from only one place in the web site instead of getting and passing data in each of the different controllers that the user control is used in?

我不确定这是否有意义.是否有更好或推荐的方法来处理要在多个页面上显示的数据孤岛"?

I'm not sure if this makes sense or not. Is there a better or recommended way to handle an "island" of data that you want to display on several pages?

我来自网络表单,我可以在其中编写一个用户控件,该控件获取自己的数据并独立于使用它的任何页面的其余部分显示数据.

I'm coming from web forms where I could just write a user control that got its own data and displayed data independently from the rest of whatever page it is used on.

推荐答案

有多种方法可以做到.

基本做法是

  • 为 BaseController 中的视图填充数据(OnActionExecuting 事件)
  • 编写自定义操作过滤器
  • 编写应用程序控制器(例如在下面的链接中).

OnActionExecuting 的一个例子是

An example of OnActionExecuting will be

   [HandleError]
    public class BaseController : Controller
    {
        CourseService cs = new CourseService();
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            List<Tag> tags = cs.GetTags();
            ViewData["Tags"] = tags;
        }

    }

您可以在任何视图上使用标签"视图数据.这只是一个将用户控件呈现为附加内容的示例.

You can use the "tags" view data on any view. This is just an example of usercontrol being rendered as side content.

<div id="sidebar_b">
         <asp:ContentPlaceHolder ID="ContentReferenceB" runat="server" >
             <% Html.RenderPartial("Tags"); %>
         </asp:ContentPlaceHolder>
   </div>

我发现以下网址很有用.

I found the following URL to be useful.

http://weblogs.asp.net/stephenwalther/archive/2008/08/12/asp-net-mvc-tip-31-passing-data-to-master-pages-and-user-controls.aspx

http://blog.matthidinger.com/2008/02/21/ASPNETMVCUserControlsStartToFinish.aspx

http://www.aaronlerch.com/blog/2008/01/26/displaying-foo-on-every-page-of-an-aspnet-mvc-application/

http://blog.wekeroad.com/2008/01/07/aspnet-mvc-using-usercontrols-usefully/

这篇关于您如何在 asp.net mvc 中使用显示“孤岛"的用户控件?数据的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆