How do you use usercontrols in asp.net mvc that display an “island” of data?

二次信任 提交于 2019-12-02 14:58:56

There are multiple ways to do it.

The basic approach is

  • Populate the data for the view in the BaseController (OnActionExecuting event)
  • Writing a custom action filter
  • Writing an Application Controller (the eg. is in the below links).

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/

In the MVC Futures, available on codeplex , contains the RenderAction HtmlHelper extensions. This will allow you to create a controller for the ueser control and this controller will populate the ViewData used by the user control without having to resort to a base controller as was suggested.

In the View you would do

<% Html.RenderAction("Index", "UserControlController") %>

or one of the other overloads.

This will create an instance of the controller, execute the method and render the user control view into the main view. The main view controller does not need to know anything about the user control or its model/data.

Refactor the code that obtains the view data for this user control into it's own method, maybe even it's own model (class). Call this method from each controller that needs to populate the control and pass the results in the ViewData with a well-known key. You might even want to pass the type of the current controller to your method in case it needs to know what data to retrieve based on the base model for the controller.

 ViewData["RecentPosts"] = RecentPosts.GetRecentPosts( this.GetType() );

In your control, retrieve the data using the well-known key.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!