当我用MVC脚手架生成视图时,我需要访问当前的"控制器名称"one_answers"区域名称"。在控制器模板中,我们有以下参数:
<#@ parameter type="System.String" name="ControllerRootName" #>
<#@ parameter type="System.String" name="AreaName" #>
在我的视图模板中需要类似的参数(如list、create或details)。我怎样才能访问这两个参数?
In The view。Ps1文件传递如下参数用于创建视图
# 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
现在在View T4模板中使用MArea和MController来获取控制器名称。
下面是示例
@using (Ajax.BeginForm("CreateP", "<#= Model.MController #>",
new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = "Def",
InsertionMode = InsertionMode.Replace,
LoadingElementId="divloading",
OnSuccess = "done",
OnFailure ="FailureAlert"
}))
这是一个蹩脚的解决方案:
string controllerstring = ViewDataTypeName.Split('.').Last().ToString();
controllerstring = controllerstring + "s";
然后用作其他参数:
<a href="@Url.Action("Index","<#= controllerstring #>")" title="@Resources.Cancel">
如果您不像我一样在搭建之前更改控制器名称,您可以使用相同的规则创建控制器名称。首先,我写了一个函数在" modelmetadatfunctions .cs.include"。t4"从类中生成控制器名称。
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;
}
然后在。t4模板
中调用该函数string controllerName = GetControllerName(ViewDataTypeShortName);
像这样使用
<a href="/Panel/<#= controllerName #>/Edit/@Model.<#= pkName #>"...