I believe I just came up with a way to handle this that doesn't seem too hacky.
To restate the problem, I believe the MVC WebGrid uses reflection to set the ColumnName
property so the string you enter for that needs to be directly accessible via the object's API eg. "Id"
, "Field.Address.Name"
, etc. The problem in my case is that the value I need for my column's row comes from a Dictionary and it doesn't seem like you can pass a parameter (key, index, etc) into the ColumnName
to get the value I need.
My solution is to avoid using the ColumnName
property of the WebGrid entirely when resolving the value to be displayed. I simply enter a value for the grid's model that I know exists for the ColumnName
, in my case "Id". This is just used so the WebGrid will render. Then, since the Format
of the WebGridColumn uses a dynamic function, I can define my column value using whatever I want:
columns.Add(new WebGridColumn
{
ColumnName = "Id",
Header = field.Label,
Format = x => new HtmlString(x.Value.GetEntityFieldValue(field.Field))
});
I soon realized that this will mess up sorting. MVC WebGrid's black-box sort simply uses the ColumnName in the sort query so every column for me now has "?sort=Id". If you're not sorting, then you're OK. If you are, you'll have to implement a custom sorting solution like I'm currently doing.