WhoAmI
WhoAmI

Reputation: 43

Share Data across ASP.NET MVC application

Recently I inherited an ASP.NET MVC 4 application which is using global.asax to share data across Views.

public class MvcApplication : System.Web.HttpApplication
{
    public static List<Models.Feed> feedItems;

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        Database.DefaultConnectionFactory = new SqlConnectionFactory(@"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        GetDataFromWebService(); //expensive call
    }       
}

There are many views that use the feedItems like:

@foreach (var item in MvcApplication.feedItems)
{
    <li>@item.Title</li>                  
}

I believe the above implementation is incorrect (since the feedItems data doesn't change unless the app pool is recycled) and there should be a better way of doing this. My requirements are:

  1. Call the GetDataFromWebService method once.
  2. Share the feedItems across multiple views.

I have looked at this SO post but I'm not sure if this is suitable in my scenario, since I want the web service to be hit only one time.

What would be the best way to do this?

Thanks!

Upvotes: 1

Views: 1072

Answers (1)

Guillaume
Guillaume

Reputation: 13138

Store the variable in the session scope if you want to get it once per session.

Global.asax

   protected void Session_Start(Object sender, EventArgs e)
   {
      HttpContext.Current.Session["WebServiceData"] = GetDataFromWebService();
   }

You can use the session from a razor view.

View

@foreach (var item in (IEnumerable<WebServiceItem>)Session["WebServiceData"])
{
    <li>@item.Title</li>
}

Upvotes: 2

Related Questions