当我使用MVC脚手架生成它们时,我需要在我的视图中访问当前的“控制器名称”和“区域名称”。在控制器模板中,我们有以下参数:
<#@ parameter type="System.String" name="ControllerRootName" #>
<#@ parameter type="System.String" name="AreaName" #>
我的视图模板中需要类似的参数(如列表,创建或详细信息)。如何访问这两个参数?
答案 0 :(得分:1)
这是一个蹩脚的解决方法:
string controllerstring = ViewDataTypeName.Split('.').Last().ToString();
controllerstring = controllerstring + "s";
然后将其用作其他参数:
<a href="@Url.Action("Index","<#= controllerstring #>")" title="@Resources.Cancel">
答案 1 :(得分:1)
在view.ps1文件中,传递如下参数以创建视图
Task<string>
现在,在View T4模板中,使用MArea和MController获取控制器名称。
以下是示例
# 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
答案 2 :(得分:0)
如果在像我这样的脚手架之前不更改控制器名称,则可以使用相同的规则创建控制器名称。 首先,我在“ ModelMetadataFunctions.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 #>"...