ASP.NET MVC code example: calling one Action from another, using the same View

Sample code: how to call an Action from within another Action, and set a specific View, in an ASP.NET MVC web application

Today I encountered a real-world scenario in which it was convenient to call one action from another, using the same view in both cases. The way to do this isn't as obvious as it could be just by using intellisense or inspecting the object model, so I've posting the code here in case anybody else finds it useful. Sample code doesn't get much simpler than this!

As you can see, one action can be a wrapper for another, and by casting we can specify which view to use. If we didn't specify the view, obviously the framework would default to name-based mapping and seek a View with the same filename as the Action.

using System.Web.Mvc;
 
namespace Website.Controllers
{
    public class TestController : Controller
    {
        public ActionResult Index()
        {
            //// Code for this "Index" action can be written here.
 
            return View();
        }
 
        public ActionResult Index2()
        {
            var viewResult = Index() as ViewResult;
 
            if (viewResult != null)
            {
                viewResult.ViewName = "~/Views/Player/LiveAudio.aspx";
            }
 
            //// Code specific to this "Index2" action can be written here.
 
            return viewResult;
        }
    }
}

In your own code, obviously you should use appropriate method names. In your application, obviously you would have additional code in each action, otherwise you could just map different routes to the same Action. The nomenclature in my example is purely to demonstrate the basic concepts as simply as possible.

Performance tip: You may want to explicitly specify the view, even though it's optional. It's great that we don't have to explicitly specify the view in ASP.NET MVC. It facilitates very easy, very rapid development. It's one less thing to think about. BUT if performance is a major consideration, setting the view file can be a good idea, because the default "conditional mapping" type behaviour searches all of the most likely folders for a View file with a filename matching the Action name.

23 June 2010

Share the love:

Comments: 1

Add Comment


Great blog explaining more on ASP.NET MVC Control. Nice sample on how to call action from another action using ActionResult, Viewresult. Thanks.

http://www.m6.net

Tags:


  • Twitter
  • LinkedIn
  • Facebook
  • Windows Live / Messenger
  • Xbox Live
  • RSS
  • Email