c# – asp mvc razor存储lambda表达式以列出并重用它

我正在使用asp.mvc 4. Assumend我有一个名为Person的模型字段

public class Person
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string SecondName { get; set; }
    public DateTime DateOfBirth { get; set; }
    public DateTime DateOfWorkstart { get; set; }
    public int NumberOfChildren { get; set; }
    public int DepartmentID { get; set; }
    public virtual Department Department { get; set; }
}

public class Department
{
    public int ID { get; set; }
    public int NameOfDepartment { get; set; }
}

在我自动生成的剃刀编辑视图字段中显示如下(为清晰起见,我在此帖中仅包含重要行)

@Html.DisplayFor(modelItem => item.FirstName)
@Html.DisplayFor(modelItem => item.SecondName)

现在我想将linq-lambda表达式存储在一个列表中,稍后再使用它,我不知道该怎么做,我需要这样的东西:

@{
    string itemsToShow = "namepart"; // this could also be "otherpart"
    List <Expression<>> list = new List();
    if (itemsToShow.equals("namepart")
    {
        list.add(modelItem => item.FirstName);
        list.add(modelItem => item.SecondName);
    }
    else
    {
        list.add(modelItem => item.DateOfBirth);
        list.add(modelItem => item.DateOfWorkStart);
        list.add(modelItem => item.NumberOfChildren);
    }
}

最后我想像这样使用生成的列表

@foreach (var lambda in list)
{
    @Html.DisplayFor(lambda)
}

最佳答案 我会为此写一个自定义助手:

public static class HtmlExtensions
{
    public static IHtmlString MyHelper(this HtmlHelper<MyViewModel> html, string itemsToShow)
    {
        var sb = new StringBuilder();
        if (itemsToShow == "namepart")
        {
            sb.Append(html.DisplayFor(x => x.FirstName));
            sb.Append(html.DisplayFor(x => x.SecondName));
        }
        else
        {
            sb.Append(html.DisplayFor(x => x.DateOfBirth));
            sb.Append(html.DisplayFor(x => x.DateOfWorkStart));
            sb.Append(html.DisplayFor(x => x.NumberOfChildren));
        }
        return new HtmlString(sb.ToString());
    }
}

然后简单地在视图内:

@Html.MyHelper("namepart")

如果你想渲染其他部分:

@Html.MyHelper("otherpart")

作为替代方案,只需将此内容放入2个不同的局部视图中,然后:

@if (itemsToShow == "namepart")
{
    @Html.Partial("_NamePart", Model)
}
else
{
    @Html.Partial("_OtherPart", Model)
}
点赞