0

Ajax を使用して Web フォームで送信するユーザー コントロールとパラメーターに関して問題があります。ラベルのみを含むユーザー コントロールを使用しています。

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

そして、このユーザー コントロールを含む Web フォーム。Webフォームでユーザーコントロールを動的に作成しています(コードビハインド):

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();
            }
        }
    }
}

次のように、Web フォームからユーザー コントロールにパラメーターを渡します。

    <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>

問題は、ボタンを数回クリックすると、「コンテンツ」の値が 1 回だけではなく数回複製され、テキストボックスに割り当てた新しい値が再入力されることです。誰かが理由を知っていますか?ボタンをクリックするたびに、ユーザーコントロールが値を受け取り、情報を一度だけ入力し、数回入力しないようにします。

4

1 に答える 1

1

交換

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

$("#Content").html(r.d);
于 2013-08-25T01:18:51.753 に答える