2

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.

Community
  • 1
  • 1
pdjota
  • 3,163
  • 2
  • 23
  • 33

2 Answers2

3

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.

nemesv
  • 138,284
  • 16
  • 416
  • 359
0

The only benefit I can see for making them virtual is to allow the developer to 'Go to Implementation/Definition' where The T4MVC helpers are used. This works because the Controller's type on the static Helper 'MVC' is the base controller type.

public static partial class MVC
{
    public static HomeController Home = new T4MVC_HomeController();
}

So in the following snippet, Go to Definition on the Action Name will go to Base Implementation:

@Url.Action(MVC.Home.Index())

+1 David Ebbo for such an intuitive feature. I was mind blown when I realized this!

PS: this does not work for the parameterless actions added via the partial function, instead they navigate to the generated code, unfortunately.

Lawrence Ward
  • 549
  • 1
  • 5
  • 17