Search code examples
c#webgrid

WebGridColumns working differently in Model


I want to make dynamic WebGridColumns. It works great in my cshtml page, but when I move it to the model I get an error:

The best overloaded method match for 'System.Web.Helpers.WebGrid.Column(string, string, System.Func<dynamic,object>,string,bool)' has some invalid arguments

Here's my Model, note that I simply copied over working code from the cshtml file.

public IHtmlString CreateTable(String name)
{
  ...
  WebGrid grid = new WebGrid(source: data, ajaxUpdateContainerId: name); 
  List<WebGridColumn> cols = new List<WebGridColumn>();
  foreach (var c in grid.ColumnNames)
  {
    cols.Add(grid.Column(c, c, format: @<text><span id="@c">@item[c]</span></text>, style: ""));
  }
  return grid.GetHtml();
}

So the error is happening after cols.Add( and then there's a bunch of different errors after that, almost as if I didn't close a bracket or something.

Do the requirements for creating a WebGridColumn change from Views to Models?


Solution

  • After many failed attempts and bizarre errors this is what finally worked:

    cols.Add(grid.Column(c, c, 
        item => 
        { 
            HtmlString h = new HtmlString("<span id=\"" + c + "\">" + item[c] + "</span>"); 
            return h; 
        },
        "", true));
    

    And even this was strung together from so many different sources I don't know where to start citing them.

    It seems like I'm doing something inherently wrong here, like I'm hitting a square peg through a circle shape, so I won't mark this as the answer right away. If you can help me understand why or what I should have done instead, I'll give you the credit.