我正在尝试修改支撑控制器的模板,检查模型是否包含某些属性,如果是,请编写c#代码为其分配一些值。所以在我的模板中,在编写Create actionresult(post)的部分中:
[HttpPost]
[ValidateAntiForgeryToken]
<# if (UseAsync) { #>
public async Task<ActionResult> Create(<#= bindAttribute #><#= ModelTypeName #> <#= ModelVariable #>)
<# } else { #>
public ActionResult Create(<#= bindAttribute #><#= ModelTypeName #> <#= ModelVariable #>)
<# } #>
{
<#
if (THE MODEL CONTAINS A PROPERTY NAMED "creation_date")) {
#>
<#= modelVariable #>.creation_date = DateTime.Now;
<# } #>
有办法吗?
答案 0 :(得分:0)
好的,我自己找到了答案,不确定它是最好的解决方案,但它运作得很好:
<#
bool entityWithCreationDate = false;
foreach (PropertyMetadata property in ModelMetadata.Properties) {
if(property.PropertyName == "creation_date") { entityWithCreationDate=true; break; }
}
if(entityWithCreationDate==true) {
#>
<#= ModelVariable #>.creation_date = DateTime.Now;
<#
}
#>