<< Click to Display Table of Contents >> JQuery - Reordenar lista de fotos |
![]() ![]() ![]() |
Objetivo
Várias imagens e o usuário pode arrastá-las e reordenar a lista.
O exemplo é bem completo, se baseia em persistência em xml para poder testar um webmethod que é chamado logo que o usuário troca uma imagem de posição.
Este webmethod grava o xml as novas posições da imagem.
Tela
Mudando a ordem, o webmethod é chamado e as novas posições são gravadas num List que é persistido em um xml:
aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication6.WebForm2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="/js/jquery-ui.css" />
<style>
#sortable
{
list-style-type: none;
margin: 0;
padding: 0;
width: 100%;
}
#sortable li
{
margin: 3px 3px 3px 0;
padding: 1px;
float: left;
width: 270px;
height: 200px;
font-size: 4em;
text-align: center;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<ul id="sortable">
<asp:ListView ID="lvFotos" runat="server" OnItemDataBound="ListView1_ItemDataBound">
<ItemTemplate>
<li class="ui-state-default">
<asp:Image ID="img" runat="server" />
</ItemTemplate>
</asp:ListView>
</ul>
</form>
<script src="/js/jquery-1.9.1.js"></script>
<script src="/js/jquery-ui.js"></script>
<script>
self.sendUpdatedIndex = function ($item) {
var startIndex = $item.data("startindex") + 1;
var newIndex = $item.index() + 1;
// mudou a posição de algum item?
if (newIndex != startIndex) {
var matriz = '';
// vamos percorrer todos os li dentro de sortable
$('#sortable li').each(function (i, li) {
// para cada li, procuramos o img dentro dele
$(li).find('img').each(function (j, img) {
// o img contem o atributo codigo (id do objeto)
matriz += $(img).attr("codigo") + "=";
})
// no objeto li temos a nova posição (como começa com zero, eu acrescentei 1)
matriz += ($(li).index() + 1) + ',';
});
//console.log(matriz);
// envia novo "mapa" de posições para a funcao
PageMethods.GravarPosicao(matriz, onSucess, onError);
function onSucess(result) {
// console.log(result);
}
function onError(result) {
alert('Algo deu errado.');
}
}
}
$(function () {
$("#sortable").sortable({
placeholder: "ui-state-highlight",
cursor: 'move',
opacity: 0.4,
start: function (event, ui) {
$(ui.item).data("startindex", ui.item.index());
},
stop: function (event, ui) {
self.sendUpdatedIndex(ui.item);
}
});
$("#sortable").disableSelection();
});
</script>
</body>
</html>
cs
using System;
using System.IO;
using System.Web.Services;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using WebApplication6.persistencia;
namespace WebApplication6
{
public partial class WebForm2 : System.Web.UI.Page
{
static Fotos fotos;
static string Arquivo;
protected void Page_Load(object sender, EventArgs e)
{
Arquivo = Server.MapPath("~/persistencia/dados.xml");
fotos = new Fotos();
if (!IsPostBack)
{
CarregarDados();
lvFotos.DataSource = fotos.Items;
lvFotos.DataBind();
}
}
[WebMethod]
public static string GravarPosicao(string matriz)
{
// matriz = 2=1,3=2,4=3,5=4,6=5,7=6,8=7,9=8,10=9,11=10,12=11,13=12,1=13,
string[] items = matriz.Split(',');
// agora vamos arrumar o posicionamento
// vamos percorrer todos os registros
for (int i = 0; i < fotos.Items.Count; i++)
{
// para cada registro, percorremos a matriz que tem os id=posicao
foreach (string item in items)
// o id do item na matriz é o mesmo da registro?
if (int.Parse(item.Split('=')[0]) == fotos.Items[i].Id)
{
// coloca posição e pula pro proximo
fotos.Items[i].Posicao = int.Parse(item.Split('=')[1]);
break;
}
}
//Salvar
SalvarDados();
return "ok";
}
static public void CarregarDados()
{
if (!File.Exists(Arquivo))
CriarDados();
XmlSerializer xml = new XmlSerializer(typeof(Fotos));
using (StreamReader file = new StreamReader(Arquivo))
{
fotos = (Fotos)xml.Deserialize(file);
fotos.Items.Sort();
}
}
static public void SalvarDados()
{
XmlSerializer xml = new XmlSerializer(typeof(Fotos));
using (StreamWriter file = new StreamWriter(Arquivo))
{
xml.Serialize(file, fotos);
file.Close();
}
}
static public void CriarDados()
{
for (int i = 0; i < 13; i++)
fotos.Items.Add(new Foto() { Id = i + 1, Nome = "l" + i.ToString() + "_1.jpg", Posicao = i + 1 });
SalvarDados();
}
protected void ListView1_ItemDataBound(object sender, System.Web.UI.WebControls.ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
// pega o dataItem corrente
ListViewDataItem currentItem = (ListViewDataItem)e.Item;
Image img = (Image)e.Item.FindControl("img");
Foto foto = (Foto)currentItem.DataItem;
img.ImageUrl = "~/img/" + foto.Nome;
img.Attributes["codigo"] = foto.Id.ToString();
img.Attributes["posicao"] = foto.Posicao.ToString();
}
}
}
}
objeto auxiliar cs
using System;
using System.Collections.Generic;
namespace WebApplication6.persistencia
{
[Serializable]
public class Foto : IComparable<Foto>
{
public int Id { get; set; }
public string Nome { get; set; }
public int Posicao { get; set; }
public Foto()
{
}
public bool Equals(Foto foto)
{
if ((object)foto == null)
{
return false;
}
return foto.Id == this.Id;
}
public int CompareTo(Foto outra)
{
if (this.Posicao < outra.Posicao)
return -1;
else
if (this.Posicao > outra.Posicao)
return 1;
else
return 0;
}
}
[Serializable]
public class Fotos
{
public List<Foto> Items;
public Fotos()
{
Items = new List<Foto>();
}
}
}
projeto