Ajax function to send list of items to a C # method in Asp.net

3

I have a list of items in an ASP.NET page defined as:

<ul id="lstProdutos">
    <li id="produto" value="1">Banana</li>
    <li id="produto" value="2">Maçã</li>
    <li id="produto" value="3">Melão</li>
    <li id="produto" value="4">Abacaxi</li>
    <li id="produto" value="5">Uva</li>
</ul>

As this list is editable on the page, I would like some ajax / javascript function to call a C # method in CodeBehind (say, a WebMethod named EnviarLista() ) that would send that list of items as a parameter. This function would be called via a asp:LinkButton button named "Save".

How would this function work in ajax / javascript? How could you link this function to the "Save" button?

    
asked by anonymous 16.04.2014 / 23:27

1 answer

7

If you have any questions with BulletedList using jQuery.sortable , I have this code:

aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebLista.aspx.cs" Inherits="WebApplication1.WebLista" %>
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" />
        <script src="//code.jquery.com/jquery-1.10.2.js"></script>
        <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
        <script>        
            var sortedIDs;
            var serializeIDs;
            $(function () {
                $("#BulletedList1").sortable({
                    create: function (event, ui) {
                        serializeIDs = $(this).sortable("serialize", { key: "id" });
                        sortedIDs = $(this).sortable("toArray");
                    },
                    update: function (event, ui) {
                        serializeIDs = $(this).sortable("serialize", { key: "id" });
                        sortedIDs = $(this).sortable("toArray");
                    }
                });
                $("#BulletedList1").disableSelection();
            });        
            function Gravar() {
                var _data = JSON.stringify({ Texto: sortedIDs });            
                $.ajax({
                    type: "POST",
                    url: "WebLista.aspx/Save_Ordem",
                    data: _data,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        $("#Result").text(msg.d);
                    },
                    failure: function (response) {
                        alert(response.d);
                    }
                });
            }
      </script>
        <style>
            *, html, body {
                font-family:Arial, Tahoma, 'Courier New', 'Arial Unicode MS';
                font-size:11px;
            }
            #BulletedList1 { list-style-type: none; margin: 0; padding: 0; width: 60%; }
            #BulletedList1 li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px; }
            #BulletedList1 li span { position: absolute; margin-left: -1.3em; }
        </style>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:BulletedList ID="BulletedList1"              
                DataTextField="Numero" 
                Width="220" 
                DataValueField="Index" 
                runat="server">                        
            </asp:BulletedList>
        </div>
            <p><asp:Label Text="" ID="LblResposta" ViewStateMode="Disabled" ClientIDMode="Static" runat="server" /></p>
            <asp:Button ID="ButSalvar" OnClick="ButSalvar_Click" runat="server" Text="Button" />
            <button type="button" onclick="Gravar();">Gravar</button>
        </form>    
    </body>
    </html>

cs

using System;
using System.Web.Services;
using System.Web.UI.WebControls;
namespace WebApplication1
{
    public partial class WebLista : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {            
            if (!IsPostBack)
            {
                Call_List();
            }
            Call_List_Css();
        }
        private void Call_List()
        {
            BulletedList1.DataSource = new object[]
            {
                new {Index = 1, Numero="Numero 1"},
                new {Index = 2, Numero="Numero 2"}
            };
            BulletedList1.DataBind();            
        }
        private void Call_List_Css()
        {
            if (BulletedList1 != null && BulletedList1.Items.Count > 0)
            {
                foreach (ListItem li in BulletedList1.Items)
                {
                    li.Attributes.Add("id", string.Format("{0}", li.Value));
                    li.Attributes.Add("class", "ui-state-default");
                }
            }
        }
        protected void ButSalvar_Click(object sender, EventArgs e)
        {
            if (BulletedList1.Items.Count > 0)
            {
                LblResposta.Text = "";
                foreach (ListItem li in BulletedList1.Items)
                {                    
                    LblResposta.Text += string.Format("<p>{0} - {1}</p>", li.Value, li.Text);
                }
            }
        }
        [WebMethod()]
        public static string Save_Ordem(string[] Texto)
        {
            //aqui você ia trabalhar o código!
            //sendo que ele mandar um lista ordenada igual na tela !!!
            return "";
        }

    }
}

Browser Screen

WhenyouclickontheSaveButtonitwillsendanAjaxinJsonFormatandyouwillgettheorderestablishedonthescreenandwiththisordersavethedatainthewayyouwantintheWebMethodSave_Order:

[WebMethod()]publicstaticstringSave_Ordem(string[]Texto){//aquivocêiatrabalharocódigo!//sendoqueelemandarumlistaordenadaigualnatela!!!return"";
}

Example of what it sends:

Comments:

privatevoidCall_List(){BulletedList1.DataSource=newobject[]{new{Index=1,Numero="Numero 1"},
           new {Index = 2, Numero="Numero 2"}
       };
       BulletedList1.DataBind();            
}

Notice that the Call_List method is loading fixed data, making changes and realizing that there is a relationship with the screen ...

Another point is to change to RedirectMode.Off, in the RouteConfig of the App_Start folder, otherwise it is giving 401 error:

public static class RouteConfig
{
     public static void RegisterRoutes(RouteCollection routes)
     {
         var settings = new FriendlyUrlSettings();
         settings.AutoRedirectMode = RedirectMode.Off;
         routes.EnableFriendlyUrls(settings);
     }
}
    
17.04.2014 / 04:14