【问题标题】:Send a variable from a JavaScript script inside my ASP.NET page to a C# Function in Code-Behind [duplicate]将变量从我的 ASP.NET 页面中的 JavaScript 脚本发送到代码隐藏中的 C# 函数 [重复]
【发布时间】:2015-05-26 14:07:12
【问题描述】:

我有我的 ASP.NET C# 网站,并且我的一个页面中有一些 JavaScript 脚本,我已经成功地从我的代码背后调用了一个 C# 函数,但我想从我的 JavaScript 脚本中发送一些变量作为参数函数。

这是我的代码,包括 C# 函数调用:

<script type="text/javascript">
    $(function () {
        // Declare a proxy to reference the hub.
        var chat = $.connection.chatHub;
        // Create a function that the hub can call to broadcast messages.
        chat.client.broadcastMessage = function (name, message) {
            // Html encode display name and message.
            var encodedName = $('<div />').text(name).html();
            var encodedMsg = $('<div /> ').text(message).html();
            var tremp_id = $('<div /> ').text("<%=Request.QueryString["trempid"]%>").html();

            // Add the message to the page.
            $('#discussion').append('<li class="<%=returnLiClass()%><strong>' + encodedName
                + '</strong>:&nbsp;&nbsp;' + encodedMsg + "Tremp:" + tremp_id + '</li>');
        };
        // Get the user name and store it to prepend to messages.
        $('#displayname').val('<%=returnName()%>');
        // Set initial focus to message input box.
        $('#message').focus();
        // Start the connection.
        $.connection.hub.start().done(function () {
            $('#sendmessage').click(function () {
                // Call the Send method on the hub.
                chat.server.send($('#displayname').val(), $('#message').val());
                // Clear text box and reset focus for next comment.
                $('#message').val('').focus();
            });
        });
    });
</script>

如您所见,我正在调用“returnLiClass()”函数(第 13 行),我想在其中发送“encodedMsg”变量。

我该怎么做?谢谢!

【问题讨论】:

  • 您可以使用的一种技术是将您的值放在具有 runat="server" 属性的隐藏字段中。

标签: javascript c# jquery asp.net .net


【解决方案1】:

Hub 类中放置一个名称与客户端方法相同的函数。

void broadcastMessage(string name, string message)
{
   //Do something here.....
}

请注意参数名称必须相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 2014-06-01
    • 2012-03-11
    • 2010-09-10
    • 1970-01-01
    • 2018-08-21
    相关资源
    最近更新 更多