Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Handling Unknown Actions in ASP.NET MVC

0.00/5 (No votes)
15 Aug 2009 1  
In this article, I will explore handling unknown actions. A Controller.HandleUnknownAction method gets called when a controller cannot find an action method that matches a browser request.

Introduction

A Controller.HandleUnknownAction method gets called when a controller cannot find an action method that matches a browser request.

Background

In this article, I will explore handling unknown actions. A Controller.HandleUnknownAction method gets called when a controller cannot find an action method that matches a browser request. I have implemented the following method in my previous article: Implementing HTTP File Upload with ASP.NET MVC.

Here is the syntax in C#:

protected virtual void HandleUnknownAction(string actionName) 

Here is a FileUploadController class that implements HandleUnknownAction as shown below:

[HandleError]
public class FileUploadController : Controller 
{ 
    public ActionResult FileUpload() 
    {
        return View(); 
    } 
    [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult FileUpload(HttpPostedFileBase uploadFile) 
    { 
        if (uploadFile.ContentLength > 0) 
        { 
            string filePath = 
               Path.Combine(HttpContext.Server.MapPath("../Uploads"), 
                            Path.GetFileName(uploadFile.FileName)); 
            uploadFile.SaveAs(filePath); 
        } 
        return View(); 
    } 
    protected override void HandleUnknownAction(string actionName) 
    { 
        actionName = "FileUpload";
        this.View(actionName).ExecuteResult(this.ControllerContext); 
    } 
}

The above example displays the FileUpload view when a request for the FileUpload action is made on the controller. If there is no matching view, then the FileUpload controller HandleUnknownAction() method is invoked. I have hard coded the FileUpload view so that if the browser request does not match the FileUpload, it will explicitly call the FileUpload action. Here is the view with the unknown action:

Notice that the controller does not have the UploadToGoogle action, but our HandleUnknownAction() method is invoked and it explicitly calls the FileUpload action.

Summary

A Controller.HandleUnknownAction method gets called when a controller cannot find an action method that matches a browser request. Therefore, in your controller class, you don’t need to explicitly code an action method for each view.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here