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




ActionResult" is an abstract class while "ViewResult" derives from "ActionResult" class. "ActionResult" has several derived classes like "ViewResult" ,"JsonResult" , "FileStreamResult" and so on.

"ActionResult" can be used to exploit polymorphism and dynamism. So if you are returning different types of view dynamically "ActionResult" is the best thing. For example in the below code snippet you can see we have a simple action called as "DynamicView". Depending on the flag ("IsHtmlView") it will either return "ViewResult" or "JsonResult".







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/MyFolder/MyPage.aspx";
            }
 
            //// Code specific to this "Index2" action can be written here.
 
            return viewResult;
        }
    }
}

Post a Comment

0 Comments