سؤال

Mono/.NET 4 MVC4 view viewmodel contains list of rows of dynamic type. This list is returned from database using WebMatrix Query() method. Dynamic type is used since number of returned columns is not known at design time, user can select different select statements.

public class HtmlReportViewModel {
  public IEnumerable<dynamic> Rows { get; set; }
  }

How to show query result in view to user in raw format ?

I tried Razor view

<body><table>
  @foreach (var r in Model.Rows)
  {
  <tr> @r.ToString() </tr>
  }
</table>
</body>

but this outputs

WebMatrix.Data.DynamicRecord 

for every row. How to show row data values in html table elemet or in other tabular form ? It there some helper for MVC4 which generates html element from this ? Applicaton should run under Mono also so I'm not sure can WebGrid used for this. Don't know is WebGrid avaliable in Mono.

It is possible to use ADO.NET DataReader in addition to WebMatrix Query() to get dynamic data if this is helps.

هل كانت مفيدة؟

المحلول

I don't know about your values, but maybe this Extension method will help:

public static class MyHtmlExtensions
{
  public static string DisplayForDynamicModel(this HtmlHelper html, dynamic model)
    {
        Type t = model.GetType();

        var props = t.GetProperties();

        StringBuilder sb = new StringBuilder();
        foreach (var p in props)
        {
           string value =  p.GetValue(model).ToString();
           sb.AppendFormat("<tr>{0}</tr>", value);
        }

        return sb.ToString();
    }
}

You can use it like this:

@foreach (var r in Model.Rows)
{
    @Html.DisplayForDynamicModel(r)
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top