如何在 asp.net 中更改文本框的事件时调用Web方法

How to call web method on change event of textbox in asp.net

本文关键字:事件 调用 方法 Web 文本 asp net      更新时间:2023-09-26

我有一个文本框。在其输入中,我想将其数据保存为粘性注释,我的意思是 asp.net 中的"自动保存"文本框。

我的前端代码是:

<textarea id="txtClientArea" runat="server" class="scfMultipleLineTextBox" cols="20" rows="4" onchange="onTextChange" >

我的javascript Web方法是:

function onTextChange(data) {
        debugger;
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "StickyNote.aspx/SaveData",
            data: JSON.stringify({ "data": data }),
            datatype: "json",
            async: false,
            success: function (response) {
                alert("C# method calling : " + response.d);
            },
            error: function (err) {
                alert(err.responseText);
            }
        });
    }

代码隐藏方法是:

[System.Web.Services.WebMethod]
public static void SaveData(string data)
{
    User currentUser = Sitecore.Context.User;
    if (currentUser != null)
    {
        currentUser.Profile.SetCustomProperty("StickyNote", data);
    }
}

如何使文本框数据自动保存?

您可以尝试以下操作:

$('#<%=txtClientArea.ClientID%>').on('change',function () {
    var data = encodeURIComponent($(this).text());                
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "StickyNote.aspx/SaveData",
        data: JSON.stringify({ "data": data }),
        datatype: "json",
        async: false,
        success: function (response) {
            alert("C# method calling : " + response.d);
        },
        error: function (err) {
            alert(err.responseText);
        }
    });
});