【问题标题】:.net MVC scaffold template: Check if model contains property.net MVC 脚手架模板:检查模型是否包含属性
【发布时间】:2017-07-30 15:30:23
【问题描述】:

我正在尝试修改构建控制器的模板,以检查模型是否包含某些属性,如果是,则编写 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;
    <# } #>

有办法吗?

【问题讨论】:

    标签: c# .net asp.net-mvc t4


    【解决方案1】:

    好的,我自己找到了答案,不确定它是否是最好的解决方案,但效果很好:

    <#
    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;      
    <#
    }
    #>
    

    【讨论】:

    • 你可以通过使用 LINQ if (ModelMetadata.Properties.Any(c=&gt;c.PropertyName=="creation_date")) {...} 来简化它
    猜你喜欢
    • 1970-01-01
    • 2011-10-09
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 2023-02-18
    • 2016-08-07
    • 2016-01-20
    • 1970-01-01
    相关资源
    最近更新 更多