Use MVCContrib grid for editing

jlembke picture jlembke · May 6, 2009 · Viewed 11.7k times · Source

I just started using the MVCContrib grid in a test project. I'm having a difficult time finding information on how to use it for edit/update/delete.

Can anyone point me to information on how to put a row into edit mode, or if there isn't such a thing for that grid, discuss a best practice for editing list data in MVC.

Answer

Marnix van Valen picture Marnix van Valen · Jun 16, 2009

You can add edit mode rendering by customizing the way a cell is rendered. I'm using the following extension method:

public static IGridColumn<T> Action<T>( this IGridColumn<T> column, Func<T, string> viewAction, Func<T, string> editAction, Func<T,bool> editMode )
{
   column.CustomItemRenderer = ( context, item ) => context.Writer.Write( "<td>" + ( editMode( item ) ? editAction( item ) : viewAction( item ) ) + "</td>" );
   return column;
}

This allows you to specify how the column is rendered in view-mode and in edit-mode. The mode is determined using a third action that should evaluate to true for the row you want to edit.

Using this in a view would look something like this:

<%= Html.Grid( Model.Items ).Columns( column => {
     column.For( x => x.Name ).Action(
        item => Html.ActionLink( item.Name, "SomeAction" ), 
        item => Html.TextBox( "Item.Name", item.Name ),
        item => ( Model.SelectedItem == item ) );
    } )
    .Empty("No items found.")
%>

You can use the same pattern to render action links (edit, apply, cancel etc.) in a cell. If you want to edit multiple rows at once, make sure the field names are unique.