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

Asked

Viewed 5,051 times

3

I have a list of items on 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>

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

What would this function look like in ajax/javascript? How could you link this function to the "Save"?

  • Using Bulletedlist and jQuery.sortable ... ?

  • That’s right! I didn’t say it before because in the end, a Bulletedlist turns it up there, but the example you showed below is exactly the way it is in my program.

1 answer

7


If your doubt is with Bulletedlist using jQuery.sortable, have that 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 "";
        }

    }
}

Screen in the Browser

inserir a descrição da imagem aqui

By clicking the Save button it will send an Ajax in Json Format and you will pick up the order established on the screen and with that order record the data the way you want in Web Method Save_order:

[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 "";
}

Example of what he sends: inserir a descrição da imagem aqui

Remarks:

private void Call_List()
{
       BulletedList1.DataSource = new object[]
       {
           new {Index = 1, Numero="Numero 1"},
           new {Index = 2, Numero="Numero 2"}
       };
       BulletedList1.DataBind();            
}

Note that the Call_list method is loading fixed data, make the appropriate changes and realize that this is related to the screen ...

Another point is to switch to Redirectmode.Off, in the Routeconfig of the App_start folder, otherwise giving error 401:

public static class RouteConfig
{
     public static void RegisterRoutes(RouteCollection routes)
     {
         var settings = new FriendlyUrlSettings();
         settings.AutoRedirectMode = RedirectMode.Off;
         routes.EnableFriendlyUrls(settings);
     }
}
  • Dude, this is exactly what I’m looking for. I just have no way to test now in my project, but as it is the first solution that appeared here, it is already worth! Thank you!

  • If you copy the font already has an example page !!!

  • I tested it here and it worked, I just had to adjust some details here. But somehow, the Save button doesn’t work... in the browser, the console says: "Failed to load resource: the server responded with a status of 404 (Not Found)". The code is exactly as above. Any idea what?

  • 1

    I disabled what I remember now: in App_start, in Routeconfig.Cs I left it like this: Settings.Autoredirectmode = Redirectmode.Off; I edited in the post as Obs

  • Okay, it worked now! It wasn’t even that, it was something else I had forgotten to change... hehehe But thank you very much!

  • What was ... kkk ?

  • I had forgotten to change the url in the Record Function because I had changed the name of Webmethod... (shame on me)

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.