c# - 如何从另一个类访问 ImageButton 控件?

标签 c# webforms

JS代码:

<script type="text/javascript">
         function ShowCurrentTime(name) {
         PageMethods.GetCurrentTime(name, OnSuccess);
         }
         function OnSuccess(response, userContext, methodName) {
          alert(response);
         }
</script>

HTML代码:

<asp:ImageButton ID="IMGBTN001" runat="server" ImageUrl="Images/ico/labaniat.png"
class="img-responsive em-img-lazy" OnClientClick="ShowCurrentTime('01')" />

<asp:Image class="img-responsive retina-img em-img-lazy" ID="IMGMostViewed" runat="server"ImageUrl="Images/Banner/block1_banner.jpg" />

C# 代码

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    //string x = IMGMostViewed.ImageUrl;
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
            + DateTime.Now.ToString();
}

我想从另一个类访问图像。

如何访问 IMGMostViewed 这个 GetCurrentTime 类?

我使用了这段代码,但得到“page.FindControl("IMGMostViewed")”返回空值

    [System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    if (HttpContext.Current != null)
    {
        Page page = (Page)HttpContext.Current.Handler;
        Image IMGMostViewed = (Image)page.FindControl("IMGMostViewed");
        string x = IMGMostViewed.ImageUrl;
    }
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
            + DateTime.Now.ToString();
}

最佳答案

理论上,您可以将 CurrentHandler 转换为您的页面类型,然后访问您的按钮:

var currentHandler = HttpContext.Current.CurrentHandler as T;
currentHandler.IMGBTN001.ImageUrl = "abc";

更好的方法是在成功函数中访问客户端的按钮。

     function ShowCurrentTime(name) {
      PageMethods.GetCurrentTime(name, OnSuccess);
     }
     function OnSuccess(response, userContext, methodName) {
      //Access here your button and modify it
     }

在这里你也会找到一个相关的答案: How to access page controls inside a static web method?

关于c# - 如何从另一个类访问 ImageButton 控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38177594/

相关文章:

c# - 处理多个 IF 语句的最佳用途

c# - ASP.NET 4.0 中的代码访问安全性和动态数据错误

asp.net-mvc - ASP.NET MVC 我应该先学习 Webform 吗?

c# - 使用面板 RenderControl 方法时无法找到具有 id 的控件

c# - 如何使用 ASP.NET Repeater 制作幻灯片

c# - 如何在 ASP.NET IDENTITY 中添加自定义表?

asp.net - 在母版页中引用样式表

c# - 如何在 .NET 中使用 Ruby 代码?

c# - 很难理解 Stack Trace

c# - 如何使用正则表达式和 C# 忽略字符串中的额外空格?