ASP.NET MVC Tip # 31 – Transfer data to Master Pages and User Controls (p1)

Tram Ho

In this tip, I suggest a method of passing data to master pages and user controls. However, before I make recommendations, I first explore several alternatives to the same problem.

The problem Imagine that you are building a movie database application with the ASP.NET MVC framework. You decide that you want to display a list of links of the movie genre with every page in your application. That way, app users can quickly navigate to their favorite movie genres. Since you want movie categories to appear on every page, it makes sense to display the categories in the app’s master page.

You also decide to display a list of featured movies on some pages, but not all pages. The list of featured movies is randomly taken from the database. You decide to deploy feature films with user control: FeaturedMovies control (see Figure 1). Figure 1 – The Movie Database Application alt

This is the problem. You need to transfer the list of movie genres to your master page for each page in your application. You need to pass the list of featured movies to the user control for certain pages in your application. How do you do it?

Using Code-Behind Class The solution that looks most appealing, but the most misleading problem is to retrieve data in the Code-Behind Class of the master page and FeaturedMovies user control. The master page in Listing 1 shows all movie genres by retrieving the list of categories from a property of the code-behind class named Categories. Listing 1 – Site.Master

The code-behind class for master pageh is contained in Listing 2. Note that the code-behind class directly access MovieDataContext. All movie genres are accessed by performing a LINQ to SQL query against MovieDataContext. Listing 2 – Site.Master.cs

You can do exactly the same thing with FeaturedMovies user control. Use the FeaturedMovies code-behind class to access DataContext directly and get a list of featured movies from the database.

So why is this wrong? This is definitely a simple solution. It works, why bother?

The problem with this solution is that the code in the page-behind code cannot be tested. You cannot easily write unit tests for the Site class because the Site class inherits from the ViewMasterPage class, from the Page class. The Page class relies on the HTTP Context object and hopes to isolate your code so it can be tested.

You should try to avoid using code-behind class for your application logic when writing ASP.NET MVC application. Try to push everything back into your controllers. Controllers are designed to be tested. (Continue)

Source: https://weblogs.asp.net/stephenwalther/asp-net-mvc-tip-31-passing-data-to-master-pages-and-user-controls

Share the news now

Source : Viblo