Reputation: 1663
I need to have access to the current "controller name" and "area name" in my views when I generate them with MVC scaffolding. In the controller template, we have the following parameters:
<#@ parameter type="System.String" name="ControllerRootName" #>
<#@ parameter type="System.String" name="AreaName" #>
I need similar parameters in my view templates (Like list, create, or details). How can I get access to these two parameters?
Upvotes: 2
Views: 1269
Reputation: 11
If you don't change controller name before scaffolding like me, you can create controller name using same rules. At first i wrote a function in to "ModelMetadataFunctions.cs.include.t4" to generate controller name from class.
string GetControllerName(string className) {
var lastchar = className.Substring(className.Length - 1, 1);
string controllerName = "";
if (lastchar.ToLower() == "y")
{
controllerName = className.Substring(0, className.Length - 1)+"ies";
}
else
{
controllerName = className+"s";
}
return controllerName;
}
And then i call that function in .T4 template
string controllerName = GetControllerName(ViewDataTypeShortName);
And used like that
<a href="/Panel/<#= controllerName #>/Edit/@Model.<#= pkName #>"...
Upvotes: 1
Reputation: 84
In The view.ps1 file pass the parameters as follows for creating views
# Render the T4 template, adding the output to the Visual Studio project
$outputPath = Join-Path $outputFolderName $ViewName
Add-ProjectItemViaTemplate $outputPath -Template $Template -Model @{
IsContentPage = [bool]$Layout;
Layout = $Layout;
SectionNames = $SectionNames;
PrimarySectionName = $PrimarySectionName;
ReferenceScriptLibraries = $ReferenceScriptLibraries.ToBool();
ViewName = $ViewName;
PrimaryKeyName = $primaryKeyName;
ViewDataType = [MarshalByRefObject]$foundModelType;
ViewDataTypeName = $foundModelType.Name;
RelatedEntities = $relatedEntities;
MController = $Controller;
MArea = $Area;
} -SuccessMessage "Added $ViewName view at '{0}'" -TemplateFolders $TemplateFolders -Project $Project -CodeLanguage $CodeLanguage -Force:$Force
And Now in the View T4 template use the MArea and MController to get controller name.
Below is example
@using (Ajax.BeginForm("CreateP", "<#= Model.MController #>",
new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = "Def",
InsertionMode = InsertionMode.Replace,
LoadingElementId="divloading",
OnSuccess = "done",
OnFailure ="FailureAlert"
}))
Upvotes: 2
Reputation: 616
Here's a lame workaround:
string controllerstring = ViewDataTypeName.Split('.').Last().ToString();
controllerstring = controllerstring + "s";
Then use it as other parameters:
<a href="@Url.Action("Index","<#= controllerstring #>")" title="@Resources.Cancel">
Upvotes: 1