使用带有返回值的 C# CodeBehind 调用 jQuery 函数

Calling jQuery function using C# CodeBehind with return value

本文关键字:CodeBehind 调用 jQuery 函数 返回值      更新时间:2023-09-26

我有一个 ASP.NET 应用程序,它将用于显示来自服务器的有关自来水公司各种站点的信息。我有一个jQuery方法,它返回在div"info"中单击的超链接的文本:

<script type="text/javascript">
        $('#info a').click(function getName()
        {
            return ($(this).text());
        });
</script>

我可以使用 C# 代码隐藏来调用此方法

ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "getName()", true);

但是我无法获得它的返回值,这正是我需要的。谁能对此有所了解?

使用隐藏字段:

<input type="hidden" id="myhiddenField" name="myhiddenField" runat="server" />

和 JQuery(尚未测试过):

<script type="text/javascript">
        $('#info a').click(function getName()
        {
            $("#myhiddenField").val($(this).text());
        });
</script>

然后,您将能够访问代码中的隐藏字段 myhiddenField.Value.

或者,如果您想使用Ajax Call,请参阅此处的教程

编辑:

创建了一个小项目,以下内容对我来说效果很好(我收到警报"测试"):

 <script type="text/javascript">
        $(document).ready(function () {
            $('#info a').click(function getName() {
                // As control having runat="server" their ids get changed
                // selector would be like this 
                $("#<%= myhiddenField.ClientID %>").val($(this).text());
                alert($("#<%= myhiddenField.ClientID %>").val());
            });
        });
</script>
<div id="info">
  <a href="#">testing</a>
</div>
<input type="hidden" id="myhiddenField" name="myhiddenField" runat="server" />
您需要在

文档准备就绪后从 JavaScript 中触发按钮单击事件 ASP.NET

喜欢这个

ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "$(function() {
$( ‘#info a
‘ ).click(); });
", true);

有关更多详细信息,请参阅 Click()

试试这个在代码隐藏上调用 Javascript 函数

ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);

如果你有UpdatePanel,那么试试这样

ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);

更新的答案:

客户端

创建一个函数并将值设置为隐藏字段作为客户端,并在服务器端调用此函数并获取隐藏字段值

.JS:

  function myFunc(){
     //set you value to hiddenfield
     $(".hdfiled").val("Hello");
      alert($(".hdfiled").val());
    }

代码隐藏:这里从服务器端调用myFunc,因为您的标题说从代码隐藏调用函数

ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:myFunc(); ", true);
string getHd_Value=  myhiddenField.value;

JS小提琴检查隐藏字段值