DevExpress GridView列的扩展方法

时间:2013-11-27 19:36:52

标签: c# asp.net-mvc devexpress extension-methods

如何扩展DevExpress GridView列。 DevExpress似乎无法遵循DataAnnotations Display。

以下是我为实现此行为而放在一起的内容:

public static class Extensions
{
    public static void AddModelToGrid<T>(
        this MVCxGridViewColumnCollection devExpCollection, 
        List<T> model)
    {
        model.ForEach((obj) =>
        {
            obj.GetType().GetProperties().ToList().ForEach((prop) =>
            {
                var displayName = 
                    (DisplayAttribute)prop.GetCustomAttribute(typeof(DisplayAttribute));
                string name = null;
                if (displayName != null)
                {
                    name = displayName.Name;
                }
                else
                {
                    name = prop.Name;
                }

                devExpCollection.Add(prop.Name, name);
            });
        });
    }
}

这个想法就是这样使用它。

@using MyApp.Models

@{
    var grid = Html.DevExpress().GridView(settings =>
    {
        settings.Name = "GridView";
        settings.CallbackRouteValues = new { Controller = "Home", Action = "GridViewPartial" };

        settings.KeyFieldName = "ID";

        settings.SettingsPager.Visible = true;
        settings.Settings.ShowGroupPanel = true;
        settings.Settings.ShowFilterRow = true;
        settings.SettingsBehavior.AllowSelectByRowClick = true;

        /* This doesn't work */
        settings.Columns.AddModelToGrid<MyObject>(settings.Columns);

    });
    if (ViewData["EditError"] != null)
    {
        grid.SetEditErrorText((string)ViewData["EditError"]);
    }
}
@grid.Bind(Model).GetHtml()

我该如何实现这种行为?

1 个答案:

答案 0 :(得分:2)

public static class Extensions
{
    public static void AddModelToGrid<T>(
        this MVCxGridViewColumnCollection devExpCollection)
    {
        // you just need the T parameter, not a list
        typeof(T).GetProperties().ToList().ForEach((prop) =>
        {
            DisplayAttribute displayName = null; 

            var attributes = prop.GetCustomAttributes(true);

            foreach (var attribute in attributes)
            {
                if (attribute is DisplayAttribute)
                {
                    displayName = (DisplayAttribute)attribute;
                }
            }

            string name = null;
            if (displayName != null)
            {
                name = displayName.Name;
            }
            else
            {
                name = prop.Name;
            }

            devExpCollection.Add(prop.Name, name);
        });
    }
}

或者更简洁

typeof(T).GetProperties().ToList().ForEach((prop) =>
{                
    var attributes = prop.GetCustomAttributes(typeof(DisplayAttribute), true);
    string name = attributes.Length > 0 ? ((DisplayAttribute)attributes[0]).Name : prop.Name;
    devExpCollection.Add(prop.Name, name);
});

然后在视图中

settings.Columns.AddModelToGrid<YourType>();