Friday, March 4, 2011

MVC3 Webgrid Html helper

Friday, March 04, 2011 Posted by Andre Broers , , , , , 13 comments
In this sample I will create an MVC index page in the razor view that displays the data in a simple webgrid.

First thing we need is a model. I will use a simple Person model:
public class Person
{
    public int id { get; set; }
    public string name { get; set; }
    public int age { get; set; }

    public List<Person> GetPersons()
    {
        return new List<Person>() { new Person() { id=1, name="Andre", age=10},
                                    new Person() { id=2, name="Bennie", age=20},
                                    new Person() { id=3, name="Roel", age=30},
                                    new Person() { id=4, name="Jeroen", age=40},
                                    new Person() { id=5, name="Arjan", age=50},
                                    new Person() { id=6, name="PietJan", age=60},
                                    new Person() { id=7, name="Alex", age=70},
                                    new Person() { id=8, name="Wim", age=80},
                                    new Person() { id=9, name="Jan", age=90}};
    }}

Next we need a controller with an index method:
public class HomeController : Controller {
  Person p = new Person();
  //
  // GET: /Home/
  public ActionResult Index()
  {
    return View(p.GetPersons());
  }
}

Next thing is the view. Right click on the index body in the the controller code and select create view and VS will create the new view:
@model IEnumerable<MvcApplicationDemo.Models.Person>

@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th></th>
        <th>
            name
        </th>
        <th>
            age
        </th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.id }) |
            @Html.ActionLink("Details", "Details", new { id=item.id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.id })
        </td>
        <td>
            @item.name
        </td>
        <td>
            @item.age
        </td>
    </tr>
}
</table>

This is nothing new and display a table with the person data from the person model:


From now on it is a small change to convert the view to use the webgrid helper:
@model IEnumerable<MvcApplicationDemo.Models.Person>

@{
    ViewBag.Title = "Index";
    var grid = new WebGrid(Model);
}

<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
@grid.GetHtml()
)

In line 5 I added the declaration of the new grid with the Model as datasource. I left the ActionLink for the creation of a new record in row 11. I replaced the table with the call the grid in row 13. This is all there is to use the default webgrid. Notice the sort that is already working.


What we miss are the links Edit, Details and Delete. To add them we need a little more markup in the view:
@model IEnumerable<MvcApplicationDemo.Models.Person>

@{
    ViewBag.Title = "Index";
    var grid = new WebGrid(Model);
}

<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
@grid.GetHtml(columns: grid.Columns(
                grid.Column(
                   header: "",
                   style: "text-align-center",
                   format: (item) => new HtmlString(Html.ActionLink("Edit", "Edit", new { id = item.id }).ToString() + " | " +
                                                    Html.ActionLink("Details", "Details", new { id = item.id }).ToString() + " | " +
                                                    Html.ActionLink("Delete", "Delete", new { id = item.id }).ToString()
                                                   )
                ),
                grid.Column("name"),
                grid.Column("age")
            )
)

In lines 13 – 23 I added the columns for the grid. The first column is the most interesting. It creates a self defined column with the three actionlinks in it. The other two are the defaults for the column names.

The result is the same as the first result in this article:


But the webgrid is more powerful which I will explain in the next blog posts.

13 comments:

  1. Thanks Andre that was a big help!

    ReplyDelete
  2. I'm new to MVC 3, and this post saved me HOURS of research or trial and error.

    Thanks!

    ReplyDelete
  3. Is there any other way to edit the rows in the same page?

    ReplyDelete
  4. There are other ways. Of course I should say. When you need inline editing you can look at jqgrid http://www.trirand.com/blog/ or kendoui grid http://demos.kendoui.com/web/overview/index.html These are excellent advanced grids, but they require a bit more configuration.

    ReplyDelete
  5. Hi,

    Is there a way I can click on the column header. I mean not sort but I want to show a different view. In my case I'm showing the level 1 data and when you click on the column header, we show a different grid for level 2 for the header clicked on level 1. Thanks!

    ReplyDelete
  6. I don't know what you mean. Do you wan't a master-detail or some sort of aggregate?

    ReplyDelete
  7. My bad, I went too far in the details. This is complicated without a visual.
    I need to set the click event on the Column Header which opens a new view. So from your example, click on the Name column header and instead of sort, its a action link or routelink, that points to a different method on the same controller with a parameter.
    Hope its better this time. Thanks for your time!!

    ReplyDelete
  8. natural cure of fatty liver natural cure of fatty liver natural cure of fatty liver

    My website; fatty liver homeopathy cure

    ReplyDelete