Function 复杂函数或辅助函数

Function 复杂函数或辅助函数,function,razor,helpers,Function,Razor,Helpers,我有一个包含十几个属性的数据模型,比如value1、value2、value3(实际上它们有有有意义的名称,但这在这里并不重要) 在显示器中,我需要对每个值执行以下操作: @if (Model.Value1 >= 2) { <div class="col-sm-6 test-box-item"> <h5>@Html.DisplayNameFor(_ => Model.Value1)</h5> <div

我有一个包含十几个属性的数据模型,比如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>
}
但我不知道怎么做

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

检查这个帮助程序

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());
    }
}

很好用!谢谢
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)