【问题标题】:complex razor function or helper复杂的剃须刀功能或助手
【发布时间】:2016-01-17 03:52:27
【问题描述】:

我有一个包含十几个属性的数据模型,比如 value1、value2、value3(实际上它们有有意义的名称,但这并不重要)。

在我的显示中,我需要对每个值执行以下操作:

@if (Model.Value1 >= 2)
{ 
    <div class="col-sm-6 test-box-item">
        <h5>@Html.DisplayNameFor(_ => Model.Value1)</h5>
        <div>@Model.Value1</div>
    </div>
}

这给他们十几个。

我想创建一个@function 或@helper 并将代码简化为:

DisplayValue(_ => Model.Value1)
DisplayValue(_ => Model.Value2)
...

但不知道该怎么做。

有什么想法吗?我想我需要一个接受表达式的函数,但我真的不知道如何编写代码。

【问题讨论】:

    标签: function razor helpers


    【解决方案1】:

    检查这个助手

    public static class HmtlExtensions
    {
        public static HtmlString DisplayValue<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
        {
            if (expression == null) 
                throw (new ArgumentNullException("expression"));
    
            var result = new StringBuilder();
    
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
    
            // get value
            var _value = metadata.Model.ToString();
    
            int value = 0;
            if (int.TryParse(_value, out value) && value >= 2)
            {
                result.Append("<div class=\"col-sm-6 test-box-item\"><h5>");
                result.Append(helper.DisplayNameFor(expression));
                result.Append("</h5><div>");
                result.Append(_value);
                result.Append("</div></div>");
            }
    
            return MvcHtmlString.Create(result.ToString());
        }
    }
    

    在你看来像使用它

    @Html.DisplayValue(x => x.Value1)
    @Html.DisplayValue(x => x.Value2)
    @Html.DisplayValue(x => x.Value3)
    

    【讨论】:

    • 完美运行!谢谢。
    猜你喜欢
    • 2018-05-19
    • 2012-02-19
    • 1970-01-01
    • 2011-05-07
    • 2019-08-01
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    相关资源
    最近更新 更多