asp.net-mvc-3t4mvc

why T4MVC introduces virtual for controller actions?


Why does T4MVC uses virtual for controller methods? Changing a

public ActionResult Details (string Id)

to:

public virtual ActionResult Details (string Id)

I have already seen other questions about T4MVC but didn't understand why.


Solution

  • Usually if a framework/library needs virtual methods (see also Nhibernate) it means somewhere/sometime your methods will be overridden.

    So T4MVC marks your action methods as virtual because it's overrides them.

    Lets take a simple controller:

    public partial class HomeController : Controller
    {
        public virtual ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
    
            return View();
        }       
    }
    

    If you go to the generated HomeController.generated.cs under the T4MVC.tt you will find a generated class which inherits from your controller and overrides your action method:

    [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
    public class T4MVC_HomeController: MvcApplication8.Controllers.HomeController {
        public T4MVC_HomeController() : base(Dummy.Instance) { }
    
        public override System.Web.Mvc.ActionResult Index() {
            var callInfo = new T4MVC_ActionResult(Area, Name, ActionNames.Index);
            return callInfo;
        }
    
    }
    

    I haven't used T4MVC so I don't know why and for what purpose T4MVC creates this generated class.