Craig
Craig

Reputation: 18734

MVC3 and Table and how to generate

I have a List<> of items which I want to display in a 3 column table. So, 3 items per row. How best would I do this in an MVC3 application? I am converting from a Asp .Net app, where I created a Table in code, and then just displayed the table.

Should I return the List<> to the View, and in the view, somehow create the table cells and rows? The objects I am returning have things like description, image URL, views etc. The table will display photos.

Upvotes: 2

Views: 3549

Answers (3)

Steven
Steven

Reputation: 172865

MVC3 has a WebGrid class that renders tables:

@{
    if (!this.Model.Items.Any())
    {
        <div>No records found.</div>
    }
    else
    {
        var grid = new WebGrid(this.Model, 
            canPage: false);

        @grid.GetHtml();
    }
}

Upvotes: 1

Matt Roberts
Matt Roberts

Reputation: 26917

Here is a nice solution from Phil Haacked's blog using a tabular template, although it's MVC2 so if you're using razor not so good.

You could also opt for a "quick and dirty" solution, just iterating the List<> in the view and spitting out the HTML from there. Scott Gu gives an overview of doing this with Razor here

Upvotes: 1

jgauffin
jgauffin

Reputation: 101192

I've just released a jQuery plugin which MVC3 support (you can use view models) which generates the table for you.

https://github.com/jgauffin/Griffin.Table

Install package

install-package griffin.table.mvc3

Create a view model (Models\User.cs)

public class User
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Create a view (Views\Home\Index.cshtml)

@model GriffinTableViewModel<DemoProject.Models.User>
@{
    ViewBag.Title = "Home Page";
}

@using (Html.GriffinTableForm("myTable", new{action = "Items"})) {}

@Html.GriffinTable("myTable", Model)

<script type="text/javascript">
    $(function () {
        $('#myTable').griffinTable({ fetchAtStart: true, pageManager: $.griffinTableExtensions.pageManagers.showMoreLinkPager });
    });
</script>

Create two actions in your controller (HomeController)

public ActionResult Index()
{
    return View();
}

public ActionResult Items(GriffinTableAjaxRequest model)
{
    var users = new List<User>();
    for (int i = 0; i < 50; i++)
    {
        users.Add(new User {Id = i + 1, FirstName = "first" + i, LastName = "last" + i});

    }

    // [.. do sorting here using model.SortColumn and model.SortOrder ..]

    var pagedResult = users.Skip((model.PageNumber - 1)*model.PageSize).Take(model.PageSize);
    return this.GriffinTable(pagedResult, users.Count);
}

There are four different implementation sample usages here

Upvotes: 2

Related Questions