GarudaLead
GarudaLead

Reputation: 479

Persisting Data

I am building an MVC 4 intranet site that I would like to have persistent data with in a footer. I'm going to hold a few basic stats that are unique to each user. I want this data to persist across all pages during a user's visit to the site.

What is the best best way to persist this data? A cookie? It's just a few non-senstive bits of information that will be pulled from AD. I was thinking hidden fields but that seems a bit cumbersome.

Thanks for the insight!

Upvotes: 0

Views: 37

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239430

While you could use sessions for this task, I would caution against. Sessions should be avoided as much as possible.

You can use a child action to build the footer, using AD to get the relevant details, and then render this in your layout. If you're concerned about AD being hit every request to render the footer, then just cache the result.

public class FooController : Controller
{
    ...

    [ChildActionOnly]
    public ActionResult Footer()
    {
        // query AD and stuff the info in a view model
        return PartialView("_Footer", model);
    }
}

Then, in your layout:

@Html.Action("Footer", "Foo")

Of course, you'll need to move your current footer view code into a partial view, named _Footer.cshtml based on this example.

To cache, just prefix the child action with:

[OutputCache(Duration = 3600, VaryByCustom = "User")]

Duration is in seconds, so the above would cache for an hour. And you'll need the following method added in Global.asax:

public override string GetVaryByCustomString(HttpContext context, string custom)
{
    if (custom == "User")
    {
        if (context.Request.IsAuthenticated)
        {
            return context.User.Identity.Name;
        }
        return null;
    }

    return base.GetVaryByCustomString(context, custom);
}

Upvotes: 1

Related Questions