Controller--------------------------------------------
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
public
ActionResult VistaPartialDetalle()
{
return
PartialView("_VistaParcialEjemplo",null);
}
public static string GetValue(string parameter, string keywork)
{
string data = "";
try
{
data = parameter.Split(new[] { keywork }, StringSplitOptions.None).GetValue(1).ToString().Split('-').GetValue(0).ToString();
}
catch (Exception e)
{
//throw
}
return data;
}
[HttpPost]
public JsonResult AjaxPostMethod(string name)
{
var RowsPerPage = 10;
var PageNumber = GetValue(name, "Página actual:") == "" ? 0 :
((Convert.ToInt32(GetValue(name, "Página actual:")))-1);
var CmdPageNumber = GetValue(name, "CmdPageNumber") == "" ? "" : (GetValue(name, "CmdPageNumber"));
var ColumnSearch = GetValue(name, "ColumnSearch") == "" ? "" : (GetValue(name, "ColumnSearch"));
if (CmdPageNumber.Contains("Anterior"))
{
PageNumber--;
if (PageNumber.Equals(-1))//en caso
que soliciten página negativa
{
PageNumber = 0;
}
}
else if (CmdPageNumber.Contains("Siguiente"))
{
PageNumber++;
}
//area de paginación-----------------------------------------------------------------------------------------------
string navigationHtml = @"
<nav aria-label='Page navigation
example'>
<span id='IdCurrentPageNumber'
style=' float:right; margin-top:20px;'>Total de Páginas:{1} -
Página actual:{0} </span>
<ul
class='pagination'>
<li
class='page-item'><span class='page-link'> <span class='glyphicon
glyphicon-chevron-left' /> Anterior</span></li>
<li class='page-item'><span
class='page-link'> Siguiente <span class='glyphicon
glyphicon-chevron-right' /> </span></li>
</ul>
</nav>
<span style='clear: both;' />
";
//------------------------------------------------------------------------------------------------------------------
DataTable dtDisplay = new DataTable();
dtDisplay.Columns.Add("Id");
dtDisplay.Columns.Add("Nombre");
dtDisplay.Columns.Add("Apellido");
dtDisplay.Columns.Add("FechaNacimiento");
dtDisplay.Columns.Add("Celular");
dtDisplay.Columns.Add("Ver");
dtDisplay.Columns.Add("Link");
//1.
la paginación varia dependiendo de la versión del SQL
https://blog.sqlauthority.com/2017/02/26/pagination-sql-server-interview-question-week-111/
//2.
sustituir por el modelo
DataTable dtItems = Extensions.Execute_QueryToDataTable("EXEC
ObtenerMinionsPaginado "+ RowsPerPage + ", "+ PageNumber
+ "");
int VirtualTotal = 0;
if (dtItems.Rows.Count != 0)
{
VirtualTotal =
Convert.ToInt32(dtItems.AsEnumerable().First()["TotalVirtual"].ToString());
}
var
TotalPaginas = Math.Ceiling(Convert.ToDecimal(VirtualTotal/RowsPerPage));
navigationHtml = string.Format(navigationHtml, (PageNumber + 1), (TotalPaginas + 1) );//cantidad
de páginas
//construcción
de cada row
foreach (DataRow item in dtItems.Rows)
{
dtDisplay.Rows.Add(
item["Id"].ToString().Trim(),
item["Nombre"].ToString().Trim(),
item["Apellido"].ToString().Trim(),
item["FechaNacimiento"].ToString().Trim(),
item["Celular"].ToString().Trim(),
"<span id='IdVer"+ item["Id"].ToString() + "' class='glyphicon
glyphicon-search' aria-hidden='true' style='cursor:pointer; color:#428BCA; '
></span>",
"<a
href='https://upload.wikimedia.org/wikipedia/en/7/7d/Minions_characters.png'
target='_blank'>Abrir</a>"
);
}
var ContentResponse = Extensions.ConvertDataTableToHTML(dtDisplay,
"IdExampleTable", "");
ContentResponse = navigationHtml +
ContentResponse;//se agrega paginación
return
Json(ContentResponse);
}
}
View--------------------------------------------
@{
ViewBag.Title = "Index";
}
<button id="idMethodAjaxPost" type="button" class="btn
btn-primary">Clic para
ejecutar Ejemplo de paginación</button>
<hr />
<div id="UserContent" style="background: yellow; text-align: center; ">Por favor espere...</div>
<div id="UserMsjPost"></div>
<br/>
@*<button id="IdAnterior" type="button"
class="btn btn-primary previous" >Anterior</button>
<button id="IdSiguiente" type="button"
class="btn btn-primary next">Siguiente</button>*@
<div id="IdUrlVistaPartialDetalle" data-request-url="@Url.Action("VistaPartialDetalle", "Home")"></div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div class="row">
<iframe id="IdIframeVistaDetalle" class="col-lg-12 col-md-12 col-sm-12" frameBorder="0" src=""></iframe>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function Main() {
$("#UserContent").hide();
//Configuracion de
Dataables--------------------------------------
$('#IdExampleTable').dataTable({
"paging": false,
"destroy": true,
"bInfo": false,
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel', 'pdf', 'print'
],
"oLanguage": {
"sSearch": "Buscar en página cargada:"
}
});
//----------------------------------------------------------------
$(".page-item").click(function() {
var Flag = true;
if (Flag) {
$("#UserContent").show();
//alert($("#IdCurrentPageNumber").text());
var data = "";
data += "CmdPageNumber:" + $(this).text() + " - ";
data += "DisplayPageNumber:" + $("#IdCurrentPageNumber").text() + " -
";
ajax_post_method("/Home/AjaxPostMethod", "name", "UserMsjPost", data);
//alert($(this).text());
Flag = false;
}
});
//$('#example')
//
.on('order.dt', function () { alert('Order'); })
//
.on('search.dt', function () { alert('Search'); })
//
.on('page.dt', function () { alert('Page'); })
//
.dataTable();
$("[id*='IdVer']").click(function() {
//Abrir Iframe con Id seleccionado
$('#myModal').modal('show');
var url = $("#IdUrlVistaPartialDetalle").data('request-url');
url
+= "/?Id=" + $(this).attr('id');
$("#IdIframeVistaDetalle").attr("src", url);
});
$("#idMethodAjaxPost").click(function () {
$("#UserContent").show();
ajax_post_method("/Home/AjaxPostMethod", "name", "UserMsjPost", $("#idInputPost").val());
});
$("#idMethodAjaxGet").click(function () {
ajax_get_method("/Home/AjaxGetMethod", "name", "UserMsjGet", $("#idInputGet").val());
});
$("IdDisplay").click(function () {
});
}
$(document).ready(function () {
AjaxInit();
});
$(document).ajaxComplete(function () {
AjaxInit();
});
function AjaxInit() {
Main();
}
function ajax_post_method(path, parameterName, targetId, parameterValue) {
$.ajax({
type: "POST",
cache: false,
url: path,
data: '{"' + parameterName + '": "' + parameterValue + '" }',
contentType: "application/json;
charset=utf-8",
dataType: "json",
success: function (data) {
$("#UserContent").hide();
$("#" + targetId + "").html(data);
},
error: function () {
//alert('Por favor intente de nuevo.');
}
});
}
</script>
CREATE TABLE [dbo].[Minion](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Nombre]
[nvarchar](50) NOT NULL,
[Apellido]
[nvarchar](50) NOT NULL,
[FechaNacimiento]
[datetime] NOT NULL,
[Celular] [int]
NOT NULL,
CONSTRAINT [PK_Minion] PRIMARY
KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS
= ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Minion] ADD CONSTRAINT [DF_Minion_Nombre] DEFAULT ('') FOR [Nombre]
GO
ALTER TABLE [dbo].[Minion] ADD CONSTRAINT [DF_Minion_Apellido] DEFAULT ('') FOR [Apellido]
GO
ALTER TABLE [dbo].[Minion] ADD CONSTRAINT [DF_Minion_FechaNacimiento] DEFAULT (getdate()) FOR
[FechaNacimiento]
GO
ALTER TABLE [dbo].[Minion] ADD CONSTRAINT [DF_Minion_Celular] DEFAULT ((0)) FOR [Celular]
GO
--EXEC sp_helptext 'dbo.ObtenerMinionsPaginado'
CREATE PROCEDURE ObtenerMinionsPaginado
@RowsPerPage INT,
@PageNumber INT
AS
SELECT *,COUNT(*) OVER ( ) AS TotalVirtual
FROM dbo.Minion2
ORDER BY Id
OFFSET @PageNumber*@RowsPerPage
ROWS
FETCH NEXT @RowsPerPage ROWS ONLY
Layout--------------------------------------------
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<link href="http://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
<script src="http://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.2/js/buttons.print.min.js"></script>
No hay comentarios:
Publicar un comentario