Search code examples
asp.net-mvc-4webgrid

How to render a list in a webgrid column


My model has as one of its properties, a list of objects. I use a webgrid on the view. Right now, my view model turns that list of objects into a string and my webgrid column displays the string. I've searched the Internet for examples of how to display a list in a webgrid column, but haven't come accross anything. I did find a blog that demonstrated how to use a webgrid inside a webgrid column, but that's not exactly what I was trying to do. I've tried this, but it generates an error (cannot convert from lambda to System.Func.

format: @<text>@foreach (var p in item.PhoneList) { p.PhoneNumber; }</text>

Any help would be appreciated.


Solution

  • I just figured out how to do this myself. Short Answer: You need an HTML Helper. Here is a pretty good reference on making your own

    Basically you need to:

    1. Make a Helpers/MyHelper.cs file
    2. Make the MyHelper class static
    3. Make a new function in the MyHelper class with the following signature: public static MvcHtmlString MyFunction(this HtmlHelper helper, [input type] myInput)

    Then just add the appropriate references. Call the Helper inline like this:

    ...

    MyWebGrid.Column(format: @<text>@Html.MyFunction(@item.[ListToExtract] as List<[ListTypeToExtract>)</text>, header:...

    ...