Update Updatepanel after running ajax without page refresh

Asked

Viewed 1,024 times

0

Good afternoon, I need to update components that are inside a UpdatePanel page aspx after insertion via Ajax. The Ajax performs a function on code-behind in C#, and happens to reload the entire page.

Ajax running the Insert:

<script type="text/javascript">
    function FunctionComment(post_id, texto) {
        if (event.keyCode == 13) {
            var adv_id = $('#<%= hdfAdvogadoID.ClientID %>').val();

            try {
                $.ajax({
                    type: "POST",
                    url: 'Default.aspx/Comentar',
                    data: "{'ComentarioTexto':'" + texto
                    + "','AdvogadoID':'" + adv_id + "','PostID':'" + post_id + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: ShowMessage(" Comentadado!", 'Success', "icon fa fa-check"),
                    error: function (msg) {
                        alert(msg.d);
                    }
                });
            } catch (err) { }
        }
    }
</script>

Method responsible for entering the data into the database:

    [System.Web.Services.WebMethod]
    public static string Comentar(string ComentarioTexto, int AdvogadoID, int PostID)
    {

        if (HttpContext.Current != null)
        {
            ComentarioCRUD.SalvaComentario(ComentarioTexto, AdvogadoID, PostID);
            NotificationCRUD.AlterarFullNotificationComent();
        }

        return string.Empty;
    }

The code works perfectly but after running the page is updated whole not only the Updatepanel.

    <asp:UpdatePanel ID="UpdatePanel2" runat="server">
    <ContentTemplate>
        <asp:Repeater runat="server" ID="Repeater1" 
            OnItemDataBound="RptTime_ItemDataBound">
            <ItemTemplate>
            <codigos>....</codigos>
            <codigos>....</codigos>
                <asp:Repeater ID="RptComentario" 
                    OnItemDataBound="RptComentario_ItemDataBound" runat="server">
                    <asp:TextBox CssClass="form-control input-sm"
                        placeholder="Pressione enter para postar comentário"
                        ID="txtPost" runat="server" AutoPostBack="false" autocomplete="off"
                        onkeypress='<%# String.Format("FunctionComment(\"{0}\", this.value);", Eval("PostID")) %>'>
                    </asp:TextBox>
                    <ItemTemplate>
                    </ItemTemplate>
                </asp:Repeater>
            </ItemTemplate>
        </asp:Repeater>
    </ContentTemplate>
</asp:UpdatePanel>

You’d have to use a trigger to update only the UpdatePanel after the command success: of Ajax!?

Design: inserir a descrição da imagem aqui

  • You have a <asp:ScriptManager> in your form?

  • @Leandroangelo, yes he inherits from the master page, without <asp:ScriptManager> would give compilation error

  • Why don’t you do everything for UpdatePanel?

  • @Virgilionovic all by UpdatePanel how so? you could exemplify for me!?

  • Updatepanel, already has everything you need to update the screen, only the code snippet, would not need to do an ajax and then have it update ...

  • @Virgilionovic I’ll try using the event txtPost.TextChanged+=new EventHandler(txtPost_TextChanged); because he’s inside a Repeater

  • 1

    I’m mounting an example @Evandro, keep trying there.!

Show 2 more comments

2 answers

1

You are using the component Updatepanel who already plays the role of ajax who is trying to ask in your question, a basic example will be demonstrated with a minimal example:

How it’s gonna work:

By clicking the button a message will be sent to be added in a static list only to show that the entire page is not updated only the excerpt from the Updatepanel:

ASPX

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebFormUpdatePanel.aspx.cs" 
         Inherits="WebApplicationForms.WebFormUpdatePanel" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <h1>Sem Refresh</h1>
        <div>
            <label><%=DateTime.Now%></label>
        </div>
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
        <div>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <div>
                        <asp:TextBox runat="server" ID="TxtMensagem"></asp:TextBox>
                        <asp:Button ID="ButInserir" runat="server" Text="Inserir"
                                    OnClick="ButInserir_Click" />
                    </div>
                    <asp:Repeater ID="RptMensagem" runat="server">
                        <ItemTemplate>
                            <div>
                                <asp:Label ID="LblMensagem" runat="server" 
                                           Text='<%#Container.DataItem%>'></asp:Label>
                            </div>
                        </ItemTemplate>
                    </asp:Repeater>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

Code

using System.Collections.Generic;
namespace WebApplicationForms
{
    public partial class WebFormUpdatePanel : System.Web.UI.Page
    {
        public static List<string> Messages = new List<string>();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Messages.Clear();
                RptMensagem.DataSource = Messages;
                RptMensagem.DataBind();
            }
        }

        protected void ButInserir_Click(object sender, EventArgs e)
        {
            Messages.Add(TxtMensagem.Text);
            TxtMensagem.Text = string.Empty;
            RptMensagem.DataSource = Messages;
            RptMensagem.DataBind();
        }
    }
}

In your code instead of doing by this static method, you can put the code in the default event, for example the Button is OnClick and so on.

  • The problem I’m facing is that the TextBox has to stay inside the Repeater as it is mounted several posts on the page each with a Textbox to be commented. And I have to pass three parameters the texto, IDdoUsuário and the IDdaPostagem to save the comment. It being inside the Repeater I can’t get via C#, I need to use javascript in the client to set these parameters.

  • @Evander can do it.

  • Blz, I’ll reference the objects at the event Repeater.ItemDataBound and try to work with them.

  • @Evandro explains to me the problem is what you need to do.

  • 1

    I’ll make another attempt, and then I’ll explain in detail Virgilio

0


As the tips of @Virgilio I solved the issue in a way not very elegant but functional:

I added the event OnTextChanged in the TextBox within the Repeater:

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
    <asp:Repeater runat="server" ID="RptTime" 
        OnItemDataBound="RptTime_ItemDataBound">
        <ItemTemplate>
        <codigos>....</codigos>
        <codigos>....</codigos>
            <asp:Repeater ID="RptComentario" 
                OnItemDataBound="RptComentario_ItemDataBound" runat="server">
                   <asp:TextBox CssClass="form-control input-sm"
         placeholder="Pressione enter para postar comentário" 
             OnTextChanged="txtPost_TextChanged"
                     onkeydown='<%# String.Format("setPostID(\"{0}\", this.value);", 
         Eval("PostID")) %>' ID="txtPost" runat="server" AutoPostBack="true" 
         autocomplete="off"></asp:TextBox>
                <ItemTemplate>
                </ItemTemplate>
            </asp:Repeater>
        </ItemTemplate>
    </asp:Repeater>
</ContentTemplate>

Code-Behind C# assigns the event to ItemDataBound of Repeater:

    protected void RptTime_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {            
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            TextBox txtPost = (TextBox)e.Item.FindControl("txtPost");
            txtPost.TextChanged += new EventHandler(txtPost_TextChanged);
    }
}

Soon I created the event that runs save it in the bank, and other actions:

protected void txtPost_TextChanged(object sender, EventArgs e)
    {
        ComentarioCRUD.SalvaComentario(Convert.ToString(hdfTexto.Value), 
                Convert.ToInt32(hdfAdvogadoID.Value), 
                Convert.ToInt32(hdfPostID.Value));

        NotificationCRUD.AlterarFullNotificationComent();

        CarregaTimeline();
    }

And to get the value of TextBox used javascript:

<script type="text/javascript">
    function setPostID(post_id, txt) {
        document.getElementById("<%=hdfPostID.ClientID %>").value = post_id;
        document.getElementById("<%=hdfTexto.ClientID%>").value = txt;
    }
</script>

Running this way there is no refresh on the page only in Updatepanel!

Browser other questions tagged

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