miércoles, 30 de octubre de 2013

JqGrid y Asp.net, Maestro detalle con SubGrid (Parte 2)

Desde que escribí mi primer post sobre como utilizar JqGrid con asp.net, he recibido varias consultas sobre como realizar un maestro detalle utilizando este control de jquery.


Antes de comenzar debo mencionar que para mostrar un maestro detalle con JqGrid tenemos dos opciones:


1. Realizarlo con un subgrid

2. Utilizar dos JqGrid separados


Así que, teniendo esto en cuenta, el objetivo de este post será realizar el maestro detalle utilizando el Subgrid, que a mi parecer es mucho más agradable y por supuesto mas ordenado. Posteriormente en otro post veremos como hacerlo con 2 JqGrid separados.


Para este ejemplo, no voy a profundizar mucho en como esta formado JqGrid ni como llenar los datos, pues eso ya lo vimos en el anterior post y aplica exactamente de la misma forma para el grid padre como para el grid hijo, basicamente sería cambiar el nombre de la tabla y crea un nuevo stored procedure.


En lo que si nos vamos a enfocar es en como realizar la definición del subgrid.


Si recordamos un poco como esta conformado el JqGrid, veremos que al final de la definición del mismo este nos permite configurar las opciones adicionales que tendrá el control, como por ejemplo:

width: "850",
height: "100%


Es precisamente en esta serie de opciones donde tendremos que habilitar nuestro grid para que contenga un subgrid, esto lo hacemos agregando la opción:

subGrid: true

Luego de que hemos habilitado nuestro subgrid debemos crear la función subGridRowExpanded que será la encargada de mostrar nuestro subgrid cuando expandamos el grid padre, es precisamente dentro de esta función donde declararemos nuestro subgrid.

    /**
     * SyntaxHighlighter
     */
subGridRowExpanded: function (subgrid_id, row_id) {
         // we pass two parameters 
         // subgrid_id is a id of the div tag created whitin a table data 
         // the id of this elemenet is a combination of the "sg_" + id of the row 
         // the row_id is the id of the row 
         // If we wan to pass additinal parameters to the url we can use 
         // a method getRowData(row_id) - which returns associative array in type name-value 
         // here we can easy construct the flowing 
         var subgrid_table_id, pager_id;
         subgrid_table_id = subgrid_id + "_t";
         pager_id = "p_" + subgrid_table_id;
       $("#" + subgrid_id).html("
"); jQuery("#" + subgrid_table_id).jqGrid({ //este es mi subgrid datatype: function () { $.ajax( { url: "webservices/LoadChild.asmx/GetChilds", //PageMethod data: "{'pPageSize':'" + $("#" + subgrid_table_id).getGridParam("rowNum") + "','pCurrentPage':'" + $("#" + subgrid_table_id).getGridParam("page") + "','pSortColumn':'" + $("#" + subgrid_table_id).getGridParam("sortname") + "','id':'" + $("#" + subgrid_table_id).getGridParam("ajaxGridOptions") + "','pSortOrder':'" + $("#" + subgrid_table_id).getGridParam("sortorder") + "'}", //PageMethod Parametros de entrada dataType: "json", type: "post", contentType: "application/json; charset=utf-8", complete: function (jsondata, stat) { if (stat == "success") jQuery("#" + subgrid_table_id)[0].addJSONData(JSON.parse(jsondata.responseText).d); else alert(JSON.parse(jsondata.responseText).Message); } }); }, jsonReader: //Set the jsonReader to the JQGridJSonResponse squema to bind the data. { root: "Items", page: "CurrentPage", total: "PageCount", records: "RecordCount", repeatitems: true, cell: "Row", id: "ID" //index of the column with the PK in it }, colModel: [ { name: 'ChildId', index: 'ChildId', width: 40, align: 'left', editable: false, editrules: { edithidden: true }, hidden: true }, { name: 'ChildName', index: 'ChildName', width: 80, align: 'left', editable: true, edittype: 'text' }, { name: 'ChildLastName', index: 'ChildLastName', width: 200, align: 'left', editable: true, edittype: 'text', editoptions: { size: 20, maxlength: 30} }, { name: 'ChildBirthDate', index: 'ChildBirthDate', width: 300, align: 'left', editable: true, edittype: 'select', editoptions: { size: 20, maxlength: 30} }, { name: 'PersonId', index: 'PersonId', width: 200, align: 'left', editable: true, edittype: 'text', editoptions: { size: 20, maxlength: 30 }, formater: 'number'}], pager: pager_id, //Pager. loadtext: 'Cargando datos...', recordtext: "{0} - {1} de {2} elementos", emptyrecords: 'No hay resultados', pgtext: 'Pág: {0} de {1}', //Paging input control text format. rowNum: "10", // PageSize. ajaxGridOptions: row_id, rowList: [10, 20, 30], //Variable PageSize DropDownList. viewrecords: true, //Show the RecordCount in the pager. multiselect: false, sortname: "ChildName", //Default SortColumn sortorder: "asc", //Default SortOrder. width: "800", height: "100%", caption: "Invoice Detail" }); jQuery("#" + subgrid_table_id).jqGrid('navGrid', "#" + pager_id, { edit: false, add: false, del: false }) },
Si vemos el código anterior, la definición del subgrid es exactamente igual a como hemos realizado la definición del grid padre, solo que dentro de una función contenedora. 

 Finalmente, así se vería 

 

Por último el código de ejemplo 



Gracias a los comentarios de muchos, actualizo el post para agregar el Stored Procedure GetChilds, que lo disfruten


 
    /**
     * SyntaxHighlighter
     */
     USE [JQGrid]
 GO
 /****** Object:  StoredProcedure [dbo].[GetChilds]    Script Date: 07/27/2012 17:55:56 ******/
 SET ANSI_NULLS ON
 GO
SET QUOTED_IDENTIFIER ON
 GO
 -- GetPersons 3, 4, 'LastName', 'desc'
 ALTER procedure [dbo].[GetChilds]
 @PageSize int , 
 @CurrentPage int , 
 @SortColumn varchar(20), 
 @SortOrder varchar(4),
 @PersoId int
 as
 declare @RecordCount int
 declare @PageCount int
 declare @PageIndex int
 Select @RecordCount = count(ChildId)
 from Childs
 set @PageCount = Ceiling(cast (@RecordCount as float) / cast (@PageSize as float))
 if (@CurrentPage > @PageCount) set @CurrentPage = @PageCount
 set @PageIndex = @CurrentPage - 1
 Select RecordCount = @RecordCount, PageCount = @PageCount, CurrentPage = @CurrentPage
 declare @Query varchar(300)
 set @Query = 
    'Select ChildId, ChildName, ChildLastName, ChildBirthDate,PersonId, 
     RowNumber = ROW_NUMBER() OVER (ORDER BY ' + @SortColumn + ' ' + @SortOrder + ')
    from Childs' 
 set @Query = 
 'Select ChildId, ChildName, ChildLastName, ChildBirthDate,PersonId
  from (' + @Query + ' )as result 
 where PersonId='+ CAST(@PersoId as varchar(5)) +' and RowNumber BETWEEN ' + cast(@PageSize * @PageIndex + 1 as varchar(10)) + 'AND ' + cast(@PageSize * (@PageIndex + 1) as varchar(10)) 
   Exec (@Query)

0 comentarios:

Publicar un comentario

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Hosted Desktops