ASP.NET MVC3 WebGrid Helper and Model Metadata

♀尐吖头ヾ 提交于 2019-12-05 17:47:32

I suggest you looking into MVCContrib Grid project: http://mvccontrib.codeplex.com/wikipage?title=Grid

Don't know if you still need some help with this question, but I had a problem just like yours and that's what I did to solve it:

  1. I Used a Foreach loop to iterate through the properties
  2. Filled a variable with the name of the property
  3. Formated the column

The code that I got was something like this:

var columns = List<WebGridColumn>();
foreach (var p in ViewData.ModelMetadata.Properties.Single.Properties) {
   String propertyName = p.PropertyName;
   columns.Add(grid.Column(p.PropertyName, p.ShortDisplayName, format: item => Html.Raw(GetPropertyValue(item.Value, propertyName))));
}
@grid.GetHtml(columns: columns.ToArray());

And that's how I get the property's value:

public static object GetPropertyValue(object obj, String propertyName)
{
    if (propertyName.Contains("."))
    {
        int index = propertyName.IndexOf(".");
        object prop = obj.GetType().GetProperty(propertyName.Substring(0, index)).GetValue(obj, null);
        return GetPropertyValue(prop, propertyName.Substring(index + 1));
    }

    return obj.GetType().GetProperty(propertyName).GetValue(obj, null);
}

I really don't know if this is the best way, but it's working pretty good for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!