DiscountASP
AboutMe
About me:
Hi. My name is Farooq Kaiser and I'm a software developer from Toronto, Canada.

Handling Unknown Actions in ASP.NET MVC

by Farooq Kaiser 5. August 2009 03:57

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 will implement the following method in my previous article Implementing HTTP File Upload with ASP.NET MVC.

protected virtual void HandleUnknownAction(string actionName) 

Here is my FileUploadController class 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 to 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 browser request does not match to FileUpload it will explicitly call FileUpload action. Here is the view with unknown action.

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

Summary 

In this article, you learned how to handle Unknown Actions in ASP.NET MVC.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

.NET | asp.net | C#

Comments

Jobs Autos Real estate Videos Power by Google