开发者

Where to put controller-wide accessible objects

开发者 https://www.devze.com 2023-03-08 19:14 出处:网络
I would like give access to the (currently logged-in) user object to all controllers, and views, in my application. For example, I wa开发者_Go百科nt to put the users name in my \"sidebar\" partial, bu

I would like give access to the (currently logged-in) user object to all controllers, and views, in my application. For example, I wa开发者_Go百科nt to put the users name in my "sidebar" partial, but don't know how to access the user object since that is stored in an other controller. Thanks in advance.


You could use the Html.Action helper method. You could define a view model which will contain all the necessary information you would like to show about the currently logged in user (like his username for example) and then have a controller action which will use the User property of the controller to populate this view model and pass it to a corresponding partial view. Then inside your master page you would include this information using the Html.Action helper:

<div id="sidebar">
    @Html.Action("Index", "Users")
</div>

which will invoke the Index action of the UsersController:

public class UsersController
{
    public ActionResult Index()
    {
        UserViewModel model = ...
        return PartialView(model);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消