2011-06-17 55 views
4

我使用的是ASP.NET MVC 3 Mvccontrib格像這樣:如何在Mvccontrib網格模型中使用自定義列?

@Html.Grid(Model).Columns(column => 
{ 
    column.For(x => x.UserId).Named("ID"); 
    column.For(x => x.Name); 
    column.Custom(@<div><img src='@item.ImageUrl' alt="@item.Name"/><a href="@item.Link">@item.Name</a></div>).Named("Name"); 
    column.For(x => x.Score).Named("Score"); 
}) 

但現在我需要把這個移動到一個自定義網格模型:

@Html.MvcContrib().Grid(Model).WithModel(new MyGridModel()).Sort(ViewData["sort"] as GridSortOptions).Attributes(id => "grid", style => "width: 100%;") 

與相應的網格模型:

public class MyGridModel : GridModel<MyModel> 
{ 
    public MyGridModel() 
    { 
    Column.For(x => x.UserId); 
    Column.For(x => x.Name); 
    Column.For(x => x.ImageUrl); 
    RenderUsing(new HtmlTableGridRenderer<MyModel>()); 
    } 
} 

但是我如何在我的網格模型中執行自定義列?
Column.Custom(???);

回答

4

嘗試這樣的:

public class MyGridModel : GridModel<MyModel> 
{ 
    public MyGridModel() 
    { 
     Column.For(x => x.UserId); 
     Column.For(x => x.Name); 
     Column.Custom(MyImage); 
     Column.For(x => x.Score); 
     RenderUsing(new HtmlTableGridRenderer<MyModel>()); 
    } 

    private static IHtmlString MyImage(MyModel model) 
    { 
     var div = new TagBuilder("div"); 
     var img = new TagBuilder("img"); 
     var a = new TagBuilder("a"); 
     img.Attributes["src"] = model.ImageUrl; 
     img.Attributes["alt"] = model.Name; 
     a.Attributes["href"] = model.Link; 
     a.SetInnerText(model.Name); 

     div.InnerHtml = string.Format(
      "{0}{1}", 
      img.ToString(TagRenderMode.SelfClosing), 
      a.ToString() 
     ); 

     return MvcHtmlString.Create(div.ToString()); 
    } 
} 
+0

大。快速,準確,工作和優雅。謝謝一堆。 –

相關問題