Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get controller name in View T4 template

I have a problem similar to the one described here: MVC T4 MvcTextTemplateHost and Customized "Controller" T4 Template but hopefully, simpler.

I have a custom View templates (View.tt, Create.tt) for ASP.NET MVC project. I can't figure out how to get the controller name in these view templates. mvcHost.ControllerName and mvcHost.ControllerRootName both are null in View templates. However, somewhere in the pipeline controller name is known, since the view is created int the ControllerName folder. I want to refer to it in the template itself.

Specifically, I want to generate HTML.ActionLink("Edit", MVC.<controllername>.Edit(id)) instead of HTML.ActionLink("Edit", "Edit", new {id = item.id})

Is it possible to get the name of the controller in the View template?

like image 240
Felix Avatar asked Jun 24 '10 04:06

Felix


2 Answers

Since I by convention almost always use the same name for my Controller as I have named the Model, I use this code in my template to get the model name and therefor the controller name:

@Html.ActionLink("Create new", 
    MVC.<#= mvcHost.ViewDataTypeName.Split('.').Last() #>.Create())
like image 65
Örjan Jämte Avatar answered Nov 11 '22 01:11

Örjan Jämte


I don't think there's a way to get that info in MVC 1.0 or MVC 2. The ControllerRootName and ControllerName properties from the host are for controller T4 templates and not for view T4 templates.

I'll see if we can add more info to the T4 host to enable these properties when generating views.

The reason that the generated file shows up in the right folder is that the MVC project system takes the output of the T4 template and puts it there. The T4 system itself doesn't participate in this process.

like image 3
Eilon Avatar answered Nov 11 '22 02:11

Eilon