Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new controller class in Visual Studio with MVC?

When I create a new controller in Visual Studio with MVC It generate automatically the following code :

public class Default1Controller : Controller
{
    //
    // GET: /Default1/

    public ActionResult Index()
    {
        return View();
    }

}

My Default1Controller inherit from Controller but I work with a BaseController class and I always have to remember to change the inheritance. Is it possible to Is it possible to modify or create a new template to automatically generate a more specific code for my project?

public class Default1Controller : BaseController
{
    //
    // GET: /Default1/

    public ActionResult Index()
    {
        return View();
    }

}

Thank you,

like image 206
Bastien Vandamme Avatar asked Jun 15 '12 10:06

Bastien Vandamme


2 Answers

You need custom code generation in MVC.

The following link might be helpful.

Modifying the default code generation/scaffolding templates in ASP.NET MVC

and also

ASP.NET MVC and T4 and NerdDinner

like image 130
Asif Mushtaq Avatar answered Nov 02 '22 23:11

Asif Mushtaq


You have to modify the T4 template that's at the basis of the "Add controller" command.

Go to \Microsoft Visual Studio 11.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 3\CodeTemplates\AddController\ (replace with your version of VS and MCV) and modify the Controller.tt

The line public class <#= mvcHost.ControllerName #> : Controller should become public class <#= mvcHost.ControllerName #> : BaseController

More details can be found on Scott Hanselman's blog

like image 20
Ando Avatar answered Nov 03 '22 00:11

Ando