How to use a custom column in a Mvccontrib Grid Model?

旧街凉风 提交于 2019-12-06 02:23:51

问题


I am using a ASP.NET MVC 3 Mvccontrib grid like so:

@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");
})

But now I need to move this into a custom grid model:

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

with corresponding grid model:

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

But how can I do my custom column in my grid model?
Column.Custom(???);


回答1:


Try like this:

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


来源:https://stackoverflow.com/questions/6391737/how-to-use-a-custom-column-in-a-mvccontrib-grid-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!