I have a table that I've built using a foreach loop in MVC 4 (Razor), and I'm trying to convert it to a WebGrid to take advantage of sorting. Currently, I'm just trying to get the format
parameter to work for me so that I can recreate the columns as I need them. Here is a simple example that I can't get to work:
grid.Column(
columnName: "ChangeId",
format: (item) => @Html.DisplayFor(m => (item as ChangeStateViewModel).ChangeId)
)
This outputs nothing during rendering:
<td></td>
What am I doing wrong? I've tried removing (item) =>
and using <text>...</text>
, but that doesn't display my value either.
EDIT
If I change it to the following, as mentioned here, it does display all of the properties in the item; however, building from there just puts me right back where I was.
format: @<text>@Html.DisplayFor(x => item)</text>
EDIT2
format: @<text>@item.ChangeId</text>
works, of course, but doesn't give me the ability to provide a DisplayTemplate.
EDIT3
It looks like (item as ChangeStateViewModel).ChangeId
is giving me NULL
.. but why? It's valued if I just use @item.ChangeId
.
EDIT4
It looks like the default item provided (when you use @<text>...</text>
) is a System.Web.Helpers.WebGridRow
, which is why EDIT3 provides the behavior that it does. Something like the below will work, but only if you send it to a DisplayTemplate; for some reason, it won't show if you remove that , "DisplayAny"
part.
format: @<text>@Html.DisplayFor(x => (item as WebGridRow)["ChangeId"], "DisplayAny")</text>
That does make EDIT2 rather confusing, though.
This works, so I'm stopping here and marking this as an answer. However, if there are better ways to approach this, I'd love to hear them.
format: @<text>@Html.DisplayFor(x => (item as WebGridRow)["ChangeId"], "DisplayAny")</text>
The DisplayTemplate is required; otherwise, this won't show.