我认为最好的方法是为每个多面列创建一个单独的“类型”和模型,然后尝试在 webgrid 中显示这种类型(我在我的后半部分展示了示例)。
例如:
创建一个名为 CompensationColumn 的新“类型”(或“列”)类:
...
using System.Web.Mvc;
namespace yourproject.Columns // I put this in its own namespace/folder - you don't have to
{
public class CompensationColumn
{
public string Currency1 { get; set; }
public int Amount1 { get; set; }
public string Currency2 { get; set; }
public int Amount2 { get; set; }
public CompensationColumn(string currency_1, int amount_1, string currency_2, int amount_2)
{
Currency1 = currency_1;
Amount1 = amount_1;
Currency2 = currency_2;
Amount2 = amount_2;
}
}
}
然后在 yourproject/Shared/EditorTemplates 文件夹中创建一个名为 CompensationColumn.cshtml 的文件(如果 Shared 文件夹不存在,您也可以创建一个 view/DisplayTemplates 文件夹)。定义该列的外观,就好像它是一个自定义“类型”(根据自己的喜好修改):
@model yourproject.Columns.CompensationColumn
@if (Model != null)
{
@Model.Currency1<text> - </text>@Model.Amount1<text><p/></text>
@Model.Currency2<text> - </text>@Model.Amount2
}
else
{
}
然后在您的 Models 文件夹中,创建一个部分类来扩展您当前的 EF 表模型(文件名应该无关紧要)。我将假设您的表是“employee_table”。我还在此类中为模型添加元数据,因为如果您使用数据库优先设计,这是一个放置它的好地方:
using System.Web.Mvc;
using yourproject.Columns;
namespace yourproject.Models
{
[MetadataType(typeof(EmployeeModelMetaData))] // This links the metadata class below
public partial class employee_table // This should be the EF class name
{
[DisplayName("Compensation")]
public CompensationColumn Compensation { get; set; } // Here we add a new field for your row
}
public class EmployeeModelMetaData
{
// copy your EF class fields here and decorate them with dataannotations. This is helpful
// if you are using a database-first design as it won't get overwritten when db changes.
[DisplayName("Id")]
public int emp_id { get; set; }
[DisplayName("Amount")]
[DisplayFormat(DataFormatString = "{0:c}", ApplyFormatInEditMode = true)]
public int emp_amount1 { get; set; }
// etc . . .
}
}
我在这里对数据库优先设计做了一些假设,但如果需要,您应该能够弄清楚如何将其调整为代码优先设计。
如果您还需要一起编辑此列类型的元素,那么您需要创建一个模型绑定器,但我不会去那里,因为您只提到了显示它。
要让显示模板显示在 webgrid 中,您需要 format: webgrid 的列。在您使用 IEnumerable 模型的视图中(例如您的索引视图):
@{
var grid = new WebGrid(Model);
List<WebGridColumn> columns = new List<WebGridColumn>();
WebGridColumn col = grid.Column(columnName: "Col3", header: "Compensation", format: (item) =>
{
yourproject.Columns.CompensationColumn c = item.Compensation; return Html.DisplayFor(model => c);
} );
columns.Add(col);
}
@grid.GetHtml(columns: columns)
最后一个 sn-p 我改编自 Frédéric Blondel 的代码 here