Subscribe to this Blog

Subscribe to this Blog

ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action - Stephen Walther on ASP.NET MVC

ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

In this tip, I demonstrate how you can eliminate controller methods that simply return views. I show you how to use the HandleUnknownAction method to handle every request against a controller automatically.

I saw Phil Haack use the following tip in a demo that he presented. I thought that it was such a great idea that I had to share it.

There is no good reason to write code unless there is a good reason to write code. I discover that I write a lot of controller actions that do nothing more than return a view. For example, consider the CustomerController in Listing 1.

Listing 1 – CustomerController.vb

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.Mvc
 
Namespace Tip22.Controllers
    Public Class CustomerController
        Inherits Controller
 
        Public Function Index() As ActionResult
            Return View()
        End Function
 
        Public Function Details() As ActionResult
            Return View()
        End Function
 
        Public Function Help() As ActionResult
            Return View()
        End Function
 
    End Class
End Namespace

Listing 1 – CustomerController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace Tip22.Controllers
{
    public class CustomerController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
 
        public ActionResult Details()
        {
            return View();
        }
        public ActionResult Help()
        {
            return View();
        }
     
    }
}

This controller includes three actions that return three different views. Each of these actions contains a single line of code. In fact, each of these actions contains exactly the same line of code. This code reeks of needless work. How can we fix it?

The Controller class includes a method, named the HandleUnknownAction() method, that executes whenever you attempt to invoke an action on a controller that does not exist. The controller in Listing 2 takes advantage of the HandleUnknownAction() method to render views even when a corresponding controller method does not exist.

Listing 2 – HomeController.vb

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.Mvc
 
Namespace Tip22.Controllers
    <HandleError> _
    Public Class HomeController
        Inherits Controller
 
        Public Function Details() As ActionResult
            ViewData("message") = "Hello from controller action!"
            Return View()
        End Function
 
        Protected Overrides Sub HandleUnknownAction(ByVal actionName As String)
            Me.View(actionName).ExecuteResult(Me.ControllerContext)
        End Sub
 
    End Class
End Namespace
 

 

Listing 2 – HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace Tip22.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Details()
        {
            ViewData["message"] = "Hello from controller action!";
            return View();
        }
 
        protected override void HandleUnknownAction(string actionName)
        {
            this.View(actionName).ExecuteResult(this.ControllerContext);
        }
 
    }
}

When you use the controller in Listing 2, you can call any action and the controller will attempt to return a view that corresponds to the action. You don’t need to explicitly code an action method for each view.

Notice that the controller includes a Details() action. When you need to pass ViewData, then you need to explicitly code the action method.

Published Monday, July 21, 2008 4:12 PM by swalther
Filed under: , ,

Comments

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Monday, July 21, 2008 9:45 PM by Webdiyer

Thank you for your great tips!

# ASP.NET MVC Archived Blog Posts, Page 1

Monday, July 21, 2008 10:52 PM by ASP.NET MVC Archived Blog Posts, Page 1

Pingback from  ASP.NET MVC Archived Blog Posts, Page 1

# ASP.NET MVC Tip #22 – 无需创建 Controller Action 直接返回一个View

Monday, July 21, 2008 11:42 PM by mike108mvp

ASP.NETMVCTip#22–无需创建ControllerAction直接返回一个ViewASP.NETMVCTip#22–ReturnaViewwithoutC...

# ASP.NET MVC Tip #22 – 无需创建 Controller Action 直接返回一个View

Tuesday, July 22, 2008 12:48 AM by cnblogs.com

ASP.NET MVC Tip #22 – 无需创建 Controller Action 直接返回一个View ASP.NET MVC Tip #22 – Return a View without Creating

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Tuesday, July 22, 2008 2:44 AM by haacked

As Eilon pointed out to me, you can accomplish the same thing using routing and a parameterized action method.

Route: url="/show/{viewName}", defaults={controller="home", action=showview}

 public ActionResult ShowView(string viewName) {

   return View(viewName);

}

And now, you don't have to write action methods for each view in the views/home directory, you can just go to /show/viewname

# ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Act

Tuesday, July 22, 2008 3:53 AM by DotNetKicks.com

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# Dew Drop - July 22, 2008 | Alvin Ashcraft's Morning Dew

Pingback from  Dew Drop - July 22, 2008 | Alvin Ashcraft's Morning Dew

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Tuesday, July 22, 2008 9:18 AM by joshka

Hi Stephen.

Would it be possible to provide a full text feed from your site. I generally read your blog in an RSS reader, and this is one of the few that I have to click through to read the actual article.

A couple of suggestions for your blog theme that hopefully won't go astray - if you cssify your vb code with a vbwrapper class instead of csharpwrapper css class, you could provide some quick javascript to hide one or the other. An option to expand all code samples for easier reading would be pretty nice also. The scrolling textboxes are nice at first, but are an annoyance when you want to read the code with the article.

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Tuesday, July 22, 2008 10:46 AM by swalther

@joshka - thanks for the feedback and for reading my blog. I have to publish excerpts because feedburner places a size limit on blog entries (feedburner stops broadcasting a blog when it gets too long). I'll look into a method for hiding/displaying different code versions. Thanks!

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Tuesday, July 22, 2008 10:59 AM by fogjuice

What if the client puts in a URL for a view that does not exist?  I assume they get an error of some sort?  What if we  would like to display a "File (view) not found" page instead?

Thanks.

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Tuesday, July 22, 2008 4:39 PM by tommy

I don't see why this would be good other then for DRY.  If you go to a page that doesn't exist, you will encounter an exception (I would think, never tested it though) that the view doesn't exist.  At this point, does MVC push the user to the error page or does an ugly exception page show up?

# Lexapro.

Thursday, August 28, 2008 7:46 AM by What is lexapro.

Lexapro withdrawal.

# Lexapro 10mg.

Monday, September 01, 2008 5:48 AM by Lexapro.

Alcohol and lexapro. Why does lexapro make me sleep all the time. Lexapro. When do you feel better with 10mg lexapro.

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Saturday, October 18, 2008 3:54 PM by Andrei Rinea

Great tip! I'll try it out. I just love a DRY tip :)

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Tuesday, November 18, 2008 5:33 AM by Thor Larholm

This works great if you have actually created a corresponding view and simply want to leave out the glue code of returning a View with the same name as the action.

However, if you have not created a corresponding view you will receive an InvalidOperationException when you trigger the ExecuteResult method. This is in contrast to the "404 Not Found" message you would otherwise receive on an unknown action.

If you want to be both DRY and able to handle unknown action/view combinations you can add a custom route as suggested by "haacked" and then explicitly provide a fallback action by overriding the OnException method.

routes.MapRoute(

 "Home",

 "Home/{viewName}",

 new { controller = "Home", action = "ShowUnknownView" }

);

public ActionResult ShowUnknownView(string viewName)

{

 return View(viewName);

}

protected override void OnException(ExceptionContext filterContext)

{

 filterContext.HttpContext.Response.Redirect("/Home");

}

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Monday, March 30, 2009 11:30 AM by Hero

<a href= nicolecocoaustinvids.watersaua.info >nicole coco austin vid

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Wednesday, April 01, 2009 12:50 PM by Hero

<a href= temecasmediatakeoutcom.foodsaua.info >temeca s mediatakeout com</a>  

<a href= htt

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Tuesday, April 21, 2009 11:46 AM by Hero

<a href= mildligamentumflavum.answerauts.info >mil

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Tuesday, April 21, 2009 3:25 PM by mid anthropogenic

references home new suggests

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Monday, May 11, 2009 8:10 AM by Neo

<a href= northwestmissouristateuniverstiy.goodauts.info >northwest missouri state universtiy</a>  

<a

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Wednesday, May 13, 2009 4:47 PM by Hero

<a href= yahoocurrencyconversions.fromauts.info >yahoo currency co

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Sunday, December 27, 2009 9:04 PM by Diesel

<a href= spmlyricswhendevilstrike.withcuted.eu >spm

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Saturday, March 06, 2010 1:31 PM by Kir

<a href= http://besplatnamuzikazaski

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Friday, March 12, 2010 11:11 PM by Halo

<a href= http://howaaxiomrifles

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Saturday, March 13, 2010 8:38 AM by Halo

<a href= howtoinstallmoenshowervalve.talkpuffed.in >how to install moen shower valve</a>  

<a href

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Sunday, March 14, 2010 1:51 PM by Diesel

<a href= memphisstyespareribs.foodpuffed.in >me

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Wednesday, March 24, 2010 7:25 PM by Hero

<a href= 05pacificaserpentinebeltrouting.mightstakt

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Tuesday, April 06, 2010 3:42 PM by Dominic

<a href= howtoelimatedahardstool.daypuffed.in >how to elimated a hard stool</a>  

<a

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Wednesday, April 21, 2010 1:17 PM by Bill

<a href= autozonepartsstoreonlinereplacem

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Wednesday, April 21, 2010 11:18 PM by Heel

<a href= http://cry

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Thursday, April 22, 2010 4:52 AM by Neo

<a href= nakedzelda.steppuffed.in >naked z

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Thursday, April 22, 2010 2:22 PM by Kir

<a href= epayrolltheworknumberssm.roompuffed.in >epayro

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Sunday, April 25, 2010 11:48 AM by Aron

<a href= http://cartoonarthurandfriends

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Tuesday, April 27, 2010 8:29 PM by Halo

<a href= backgroundcourthouseefacts.laypuffed.in >b

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Sunday, May 16, 2010 4:00 PM by Jane

<a href= aspenhomeridge.doorgooded.in

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Tuesday, May 18, 2010 10:04 AM by Aron

<a href= 32ounceshowmanypounds.majorgooded.in >32 ounces how many pounds</a>  

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Tuesday, May 18, 2010 5:34 PM by Arnie

<a href= ar15trajectorycharts.liegooded.i

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Friday, May 28, 2010 6:46 AM by Dominic

<a href= blackamericanmengospelartistcd.hurrygooded.in >black american men gospel artist c d</a>  

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Saturday, May 29, 2010 2:44 PM by Heel

<a href= internetvideocom.quartgooded.i

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Saturday, June 26, 2010 10:24 AM by Arnie

<a href= 1999escortvacuumhoseroutingdiagr

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Thursday, September 02, 2010 5:06 PM by Halo

<a href= http://subgaugeshot

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Friday, September 03, 2010 4:36 AM by Heel

<a href= americanidol.wetpaint.com/.../best_dating_tec8507 >adult dating ser

# re: ASP.NET MVC Tip #22 -- Return a View without Creating a Controller Action

Monday, September 06, 2010 6:43 AM by Hero

<a href= http://stu

Leave a Comment

(required) 
(required) 
(optional)
(required)