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

In ASP.net MVC3 how to provide an link in the WebGrid


In ASP.NET MVC3 I am using a Webgrid to populate the data. I have a column in which I want the data in that column to have an action link. My Table looks like this

Roll No | StudentName  |  Class |  Course  |         |
======================================================
110     |  XY          |   5    |   Science| ViewDetails

I want to provide a link to each ViewDetails in the row so to move to the desired action.As well as I want to pass a value that is RollNo to the action. How this can be achieved. I tried something like this.

var grid = new WebGrid(source: Model, canPage: true, rowsPerPage: 10);
    grid.Pager(WebGridPagerModes.NextPrevious);
    @grid.GetHtml(tableStyle: "grid", 
        htmlAttributes: new { id = "DataTable" }, 
        headerStyle: "grid-header", 
        footerStyle: "grid-header", 
        alternatingRowStyle: "grid-alternating-row", 
        selectedRowStyle: "grid-selected-row", 
        rowStyle: "grid-row-style", 
        columns: grid.Columns(
           grid.Column(columnName: "RollNo", header: "RollNo"), 
           grid.Column(columnName: "StudentName", header: "StudentName"), 
           grid.Column(columnName: "Class", header: "Class"), 
           grid.Column(columnName: "Course", header: "Course"),
           grid.Column(header: "",
                  format:item => 
                    new HtmlString(Html.ActionLink("ViewDetails","Home")))); 

Solution

  • Do it with this crappy syntax:

    grid.Column(
        header: "Link", 
        format: @<text>@Html.ActionLink("ViewDetails", "Home")</text>)
    

    Inside the <text> block you can access the current line by using the variable item like this:

    format: @<text>@Html.ActionLink(item.Text, "Home")</text>