Reputation: 35
I am using MVC3 WebGrid control to render a list of entities. Assume I have an Index like page that renders a list of users, or items, orders etc. All these entties are having a column called ID.
The WebGrid looks well, the only thing I want is that once the list is rendered I want to add the 3 action links Edit, Delete, Detail prior to all other columns.
Adding the following code works but I don't want to repeat this code in all the pages:
@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("FirstName"),
grid.Column("LastName"),
grid.Column("EmailAddress")
)
Basically what I want is to say @Grid.Render(Model) ... and it should create the first 3 action links and they render all the columns of the model.
I know that there are JQuery grids and MVCContrib etc but they are not the option please.
Any comments and tips will be appreciated.
Upvotes: 2
Views: 9249
Reputation: 1038780
You could write a custom extension method for the grid:
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Mvc.Html;
public static class WebGridExtensions
{
public static IHtmlString MyGetHtml(this WebGrid grid, HtmlHelper html)
{
var columns =
(from n in grid.ColumnNames
select new WebGridColumn { ColumnName = n, CanSort = true }
).ToList<WebGridColumn>();
columns.Insert(0, grid.Links(html));
return grid.GetHtml(columns: columns, exclusions: new[] { "ID" });
}
public static WebGridColumn Links(this WebGrid grid, HtmlHelper html)
{
return 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()
)
);
}
}
and then use it:
@model IEnumerable<MyViewModel>
@{
var grid = new WebGrid(Model);
}
@grid.MyGetHtml(Html)
or if you want to control the building of the other columns:
@grid.GetHtml(
columns: grid.Columns(
grid.Links(Html),
grid.Column("FirstName"),
grid.Column("LastName"),
grid.Column("EmailAddress")
)
)
Upvotes: 4