[英].net MVC scaffold template: Check if model contains property
I am trying to modify the template that scaffolds a controller, to check if the model contains some property, and if so, write the c# code to assign it some value. 我正在尝试修改脚手架控制器的模板,以检查模型是否包含某些属性,如果包含,请编写c#代码为其分配一些值。 so in my template, in the part that writes the Create actionresult (post):
因此在我的模板中,编写Create actionresult(后)部分:
[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;
<# } #>
is there a way to do it? 有办法吗?
Ok I found answer myself, not sure it its the best solution but its working nicely: 好的,我找到了自己的答案,不确定它是否是最好的解决方案,但是效果很好:
<#
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;
<#
}
#>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.