【问题标题】:I need to execute Java script function from c# code behind我需要从后面的 c# 代码执行 Javascript 函数
【发布时间】:2014-04-21 13:35:37
【问题描述】:

我需要从后面的 c# 代码执行 Java 脚本函数。使用 Asp.net 服务器控制中继器并在条件为真时检查条件需要运行 java 脚本函数,该函数将打开超链接显示块这是我的 javascript 函数

function MyFunction(username) {
  document.getElementById("hyp").style.display = "block";
}

这是我在该条件之后的 Asp.net 代码,如果为真,我在方法 writeText() 后面调用 c# 代码:

<%# Eval("part2").ToString() == "part2" ? writeText(Eval("Albumtitle").ToString(), Eval("Albumtitle").ToString(), inc.ToString()) : writeLink(Eval("Albumtitle").ToString(), Eval("Albumtitle").ToString())%>

protected string writeText(string PageDataId, string AlbumId, string a)
{
    ClientScript.RegisterStartupScript(this.GetType(), "hwa", "MyFunction('Checkjj');", true);
    string html = "";
    html += "";
    return html;
}

这个 c# 调用 javascript 函数显示 html 锚以阻止在开始时不显示

这是那个锚标签

<a id="hyp" name="hyp"  href="#" class="lightbox<%=inc+"b" %>">Part II</a>

【问题讨论】:

  • 您是否遇到任何错误?
  • @SivaRajini 我收到此错误解析器错误消息:服务器标签不能包含 构造。

标签: c# javascript asp.net iis


【解决方案1】:

使用您的 html:&lt;a id="hyp" name="hyp" ... 添加属性 runat="server"。然后在服务器端,您可以像访问服务器控件一样访问该对象。

无需在服务器端执行 Javascript 即可执行您需要的操作。

类似于转发器的“ItemDataBound”事件:

  void MyRepeater_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {
string someVar = "someValue"  ;  
           ((HtmlAnchor)e.Item.FindControl("hyp")).Attributes.Add ("css", "lightbox" + someVar);          
       }  

为了使用这个事件不要忘记添加事件和runat服务器属性:

<asp:Repeater ID="MyRepeater" runat="server" OnItemDataBound="MyRepeater_ItemDataBound">

       <a id="hyp" name="hyp"  href="#" runat="server">Part II</a>

</asp:Repeater>  

您会发现此博客很有帮助:

【讨论】:

  • 如果我在标签中添加 runat 服务器,那么我不能使用 class="lightbox"> 它给我错误
  • 不正确...您可以在 itemDatabound 事件中添加它
  • 如何指导我?
  • 我刚刚添加了一个快速示例
  • @JayZee 您将runat="server" 添加到属性列表的开头,然后将类属性放在属性列表的末尾。然后运行它。它应该运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多