Let say I have an object that is similar for each user that try to access to my website. A sort of Session Scope object, which should be visible on every View/Model/Controller inside my whole "application".
I'd like to create it when I call a page and populate it through data coming from my own database.
Than, on View (as example) calling myObject.Title. On WebForms I'm doing this extending a class of the UserControl, such as:
public class iUserControl : System.Web.UI.UserControl
{
protected MyCurrentPage myCurrentPage;
public iUserControl()
{
}
protected override void OnLoad(EventArgs e)
{
myCurrentPage = new MyCurrentPageWrapper();
}
}
than, for each UserControl, somethings like this:
public partial class context_pippo_MyOwnUserControl : iUserControl
on MVC I can't see any extension for each controls, so how can I could achieve this kind of process? I'd like to get rid about storing elements on Session.
If I understand question correctly, I think I've done something similar in one project. I had something like this:
public interface IControllerBaseService
{
IUserService UserService {get;set;}
ShoppingMode ShoppingMode {get;set;}
...
}
public abstract class ControllerBase : Controller, IControllerBaseService
{
public IUserService UserService {get;set;} // this is injected by IoC
public ShoppingMode ShoppingMode
{
get
{
return UserService.CurrentShoppingMode; // this uses injected instance to get value
}
...
}
As long, as I user IoC container to create controller instances, UserService property is injected by container.
You can access now your interface from view like this:
(IControllerBaseService)ViewContext.Controller
To have a shortcuts for most common used properties in IControllerBaseService
, I had several extension methods, something like this:
public static ShoppingMode CurrentShoppingMode(this HtmlHelper helper)
{
return ((IContollerBaseService)helper.ViewContext.Controller).ShoppingMode;
}
So in view it looked like @Html.CurrentShoppingMode()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.