开发者

how to populate partial view for display on every page

This is probably a dumb question but I am trying to figure out how to populate a ViewModel for a partial view that displays t开发者_开发知识库he logged in users DisplayName. This Partial view is in the main layout so it will be on every page. Sounds simple I know; however for the life of me I can't figure out the best way to get the data to the View. How do I persist this view?


The best way would probably to use child actions along with the Html.Action helper.

So as always in ASP.NET MVC you start with a view model which will represent the information you are willing to manipulate/display in a view:

public class UserViewModel
{
    public string FullName { get; set; }
}

then a controller:

public class UsersController: Controller
{
    // TODO: usual constructor injection here for
    // a repository, etc, ..., omitted for simplicity

    public ActionResult Index()
    {
        var name = string.Empty;
        if (User.Identity.IsAuthenticated)
        {
            name = _repository.GetFullName(User.Identity.Name);
        }
        var model = new UserViewModel
        {
            FullName = name
        };
        return PartialView(model);
    }
}

a corresponding partial view:

@model UserViewModel
{
    // Just to make sure that someone doesn't modify
    // the controller code and returns a View instead of
    // a PartialView in the action because in this case
    // a StackOverflowException will be thrown (if the child action
    // is part of the layout)
    Layout = null; 
}
<div>Hello @Model.FullName</div>

then go ahead in your _Layout and include this action:

@Html.Action("Index", "Users")

Obviously the next improvement to this code would be to avoid hitting the database on each request but storing this information somewhere once the user logs in as it will be present on all pages. Excellent places for this are for example the userData part of the encrypted authentication cookie (if you are using FormsAuthentication of course), Session, ...


You could look into having a child action method.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜