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

前端 未结 4 1991
时光说笑
时光说笑 2021-01-30 09:34

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 i

4条回答
  •  遇见更好的自我
    2021-01-30 10:25

    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.

提交回复
热议问题