Friday, January 11, 2013

ASP.NET MVC 404 Content Page Show's Twice

In handling 404 pages (pages that don't exist in the website),I encountered a problem wherein the asp.content tag/control would show twice in the page. Here's the server content code:
  <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">   
   <h2>Page Not Found!</h2>   
   <br />   
   Error in URL Navigation. The page you were looking for was not found.   
  </asp:Content>  
And here's the content being displayed twice.
The code I'm using was from a documentation/series on how to handle 404 pages. The tutorial has a controller factory that checks invalid routes and calls the base controller if a route is invalid. Below is the code:
Code:
   //inherit Controller Class  
   public class BaseController : Controller   
   {  
     private string context;  
     public string MyContextUrl   
     {  
       get  
       {  
         return context;  
       }  
       set  
       {  
         if (value == null)  
         {  
           throw new NullReferenceException();  
         }  
         context = value;  
       }  
     }  
     protected override void HandleUnknownAction(string actionName)  
     {  
       RouteToPage404(HttpContext);  
     }  
     public ActionResult RouteToPage404(HttpContextBase context)  
     {       
         //errorController instance  
         IController errorController = new ErrorController();  
         RouteData rd = new RouteData();  
         rd.Values.Add("controller", "Error");  
         rd.Values.Add("action", "Http404");  
         //execute controller  
         errorController.Execute(new RequestContext(context, rd));  
         return new EmptyResult();  
     }      
   }  
In-order for content to be displayed once, add checking if the controller context is not null.
Code:
       if (this.ControllerContext != null)  
       {  
         IController errorController = new ErrorController();  
         RouteData rd = new RouteData();  
         rd.Values.Add("controller", "Error");  
         rd.Values.Add("action", "Http404");  
         //execute controller  
         errorController.Execute(new RequestContext(context, rd)); 
         errorController.Execute(new RequestContext(context, rd));  
       } 
 
         return new EmptyResult();   
The 404 controller shown only once.
The controller context is not null since ErrorController inherits base controller. The controller factory in turn
does not inherit BaseController.


Greg

0 comments:

Post a Comment