【问题标题】:How to access ImageButton control from another class?如何从另一个类访问 ImageButton 控件?
【发布时间】:2016-07-04 05:40:08
【问题描述】:

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();
}

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

如何访问 IGMMostViewed 这个 GetCurrentTime 类?

我使用了这段代码,但是得到 "page.FindControl("IMGMostViewed")" return null

    [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();
}

【问题讨论】:

    标签: c# webforms


    【解决方案1】:

    理论上,您可以将 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?

    【讨论】:

    • 感谢您的回答。 HttpContext.Current.CurrentHandler 中的“T”是什么?
    • T 应该代表你的页面,然后你有你的页面实例,你可以访问你的 imagebutton :)
    • 我用这个但是得到空引用
    • 我添加了一个链接,看看这个,如果它不能帮助再次发布您的代码(页面标记;页面代码隐藏,页面 webmethod javascript)
    • @Cyril Iselin HttpContext.Current.CurrentHandler 返回空引用?
    猜你喜欢
    • 2019-09-23
    • 1970-01-01
    • 2011-08-04
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多