2016-07-04 35 views
2

JS代碼:如何從另一個類訪問ImageButton控件?

<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 「)」 返回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(); 
} 

回答

0

Theoreticaly,就可以把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?

+0

謝謝您的回答。 HttpContext.Current.CurrentHandler中的'T'是什麼? – mohammad

+0

T應該代表你的頁面,然後你有一個你的頁面的實例,你可以訪問你的imagebutton :) –

+0

我使用這個,但得到空引用 – mohammad