loki
loki

Reputation: 2966

How to create dynamic Grid using mvc 3 aspx engine?

I am new to asp.net mvc 3.I am trying to generate a dynamic gridview using mvc3 but i cannot produce grid. My code below:

Model:


  public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public double Salary { get; set; }
        public static List<Employee> GetList()
        {
            List<Employee> employees = new List<Employee>{
          new Employee   { FirstName="Rahul", LastName="Kumar", Salary=45000},
          new Employee   { FirstName="Jose", LastName="Mathews", Salary=25000},
          new Employee   { FirstName="Ajith", LastName="Kumar", Salary=25000},
          new Employee   { FirstName="Scott", LastName="Allen", Salary=35000},
            new Employee   { FirstName="Abhishek", LastName="Nair", Salary=125000}
            };
            return employees;
        }
    }

Controller


  public class EmployeeController : Controller
    {
        //
        // GET: /Employee/

        public ActionResult Index()
        {
            var empoyees = Employee.GetList();
            return View(empoyees);
        }

    }

View:


<%
    var grid = new WebGrid(source: Model, defaultSort: "FirstName", rowsPerPage: 3);
    using (Html.BeginForm())
    {
        %>
        <div id="grid">
        <%:grid.GetHtml(tableStyle:"grid", 
        headerStyle:"head", 
        alternatingRowStyle:"alt",
        columns:grid.Columns(
        grid.Column("FirstName"),
        grid.Column("LastName"),
        grid.Column("Salary"))) %>
        </div>
        <%} %>

i want to create


grid.Column("FirstName"),
        grid.Column("LastName"),
        grid.Column("Salary"))

dynamically return controller action. How do I return dynamic column or dynamic gridview or extentions?

Upvotes: 0

Views: 4603

Answers (2)

Ramin Bateni
Ramin Bateni

Reputation: 17385

@programmerist, This is your Answer ;)

@{
    var properties = typeof(MyModelClassName).GetProperties();
    var webGridColumns = properties.Select(prop => new WebGridColumn()
        {
            ColumnName = prop.Name, Header = prop.Name, Style = "my-style"
        }).ToList();

    var grid = new WebGrid(source: Model, rowsPerPage: 3);
    @grid.GetHtml(tableStyle: "grid",
                  headerStyle: "head",
                  alternatingRowStyle: "alt",
                  columns: webGridColumns)
}

Upvotes: 1

RL89
RL89

Reputation: 1916

Try This. In this way you can create a Grid:

<table>
 <tr>
     <th>
         Item1
     </th>
     <th>
         Item2
     </th>
     <th>
         Item2
     </th>
 </tr>

<% foreach (var item in Model) { %>
    <tr>
        <td>
            <%: item.item1 %>
        </td>
        <td>
            <%: item.item2 %>
        </td>
        <td>
            <%: item.item3 %>
        </td>           
    </tr>
<% } %>
</table>

Upvotes: 0

Related Questions