我正在使用razor内联模板来定义网格列格式。
如果您在剃刀视图中定义内联模板,这项工作非常有用。
如何在控制器的代码中执行相同操作(使用内联模板定义列列表)?
答案 0 :(得分:3)
以下是示例代码。您还可以使用this获取查看代码。另请参阅this以扩展网格,
public class HomeController : Controller
{
public class Employee
{
public string Name { get; set; }
public string Description { get; set; }
public int Price { get; set; }
}
public ActionResult Index()
{
var myClasses = new List<Employee>{
new Employee { Name="A" , Price=1, Description="A A"},
new Employee { Name="B" , Price=2, Description="B B"},
new Employee { Name="C" , Price=3, Description="C C"}};
var grid = new WebGrid(source: myClasses);
var html = grid.GetHtml(
columns: grid.Columns(
grid.Column("Name", "Product", style: "product"),
grid.Column("Description", format: item => new System.Web.WebPages.HelperResult(writer =>
{
WriteLiteralTo(writer, "<i>");
WriteTo(writer, item.Description);
WriteLiteralTo(writer, "</i>");
})),
grid.Column("Price", format: item => new System.Web.WebPages.HelperResult(wrtier =>
{
WriteLiteralTo(wrtier, "$");
WriteTo(wrtier, item.Price);
}))
)
);
return View();
}
private void WriteLiteralTo(TextWriter writer, object content)
{
writer.Write(HttpUtility.HtmlEncode(content));
}
public static void WriteTo(TextWriter writer, object content)
{
writer.Write(HttpUtility.HtmlEncode(content));
}
}