Search code examples
c#asp.net-mvc-4webgrid

Understanding WebGrid in C#


I am trying to get to grips with WebGrid in a c# MVC4 project. The following code gives this error...

Compiler Error Message: CS1502: The best overloaded method match for 'System.Web.Helpers.WebGrid.WebGrid(System.Collections.Generic.IEnumerable, System.Collections.Generic.IEnumerable, string, int, bool, bool, string, string, string, string, string, string, string)' has some invalid arguments

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />

    @{
        List<int> obj1 = new List<int>(){ 1, 2, 3, 4 };
        var obj1_i = (IEnumerable<int>)obj1;       
        var grid = new WebGrid(obj1_i);
    }

</head>
<body>
    <div>
        @grid.GetHtml()
    </div>
</body>
</html>

Solution

  • The problem is that WebGrid expects your model to be IEnumerable<dynamic>, not IEnumerable<int>. Change your code to the following:

    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
    
        @{
            List<dynamic> obj1 = new List<dynamic>(){ 1, 2, 3, 4 };     
            var grid = new WebGrid(obj1);
        }
    
    </head>
    <body>
        <div>
            @grid.GetHtml()
        </div>
    </body>