Passing parameter in User control created dynamically by Ajax duplicate values

1.6k views Asked by At

I have a problem regarding User control and parameters that I send by the web form using Ajax. I’m using a user control that contains only a Label.

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Message.ascx.cs" Inherits="Message" %>
<asp:Label ID="lblMessage" runat="server" Text="lblMessage"></asp:Label>

And a web form that contains this user control. I’m creating dynamically the user control in the web form (code behind):

public partial class _Default : System.Web.UI.Page
{
    [WebMethod]
    public static string LoadUserControl(string message)
    {
        using (Page page = new Page())
        {
            UserControl userControl = (UserControl)page.LoadControl("Message.ascx");
            (userControl.FindControl("lblMessage") as Label).Text = message;
            page.Controls.Add(userControl);
            using (StringWriter writer = new StringWriter())
            {
                page.Controls.Add(userControl);
                HttpContext.Current.Server.Execute(page, writer, false);
                return writer.ToString();
            }
        }
    }
}

and passing the parameter from the web form to the user control like this:

    <script type = "text/javascript">

        $(document).ready(function(){

            $("#demo").click(function () {
                $.ajax({
                    type: "POST",
                    url: "CS.aspx/LoadUserControl",
                    data: "{message: '" + $("#message").val() + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (r) {
                        $("#Content").append(r.d);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <input type = "text" id = "message" />
    <input type = "button" id = "demo" value = "Load" />
    <div id  = "Content">

    </div>
    </form>
</body>
</html>

The problem is when I click several times the button, the value in the “Content” is duplicated several times instead only once and refilled with the new value that I assigned to the textbox. Somebody know why? I want, that every time that I click in the button, the user control receive the value and populate only once the info and not several times.

1

There are 1 answers

0
Michael B. On BEST ANSWER

replace

 $("#Content").append(r.d);

width

$("#Content").html(r.d);