2016-07-26 61 views
0

如果我使用一個頁面的方法是這樣的:如何從頁面方法訪問服務器控件?

[System.Web.Services.WebMethod] 
     public static string GetSearchResult(string searchKeyword) 
     { 
      ArrayList searchResultRows = new ArrayList(); 
      Random random = null; 
      for (int resultCount = 0; resultCount < 10; resultCount++) 
      { 
       random = new Random(resultCount); 
       searchResultRows.Add(string.Concat(searchKeyword, random.Next().ToString())); 
      } 
      GridView resultRepeater = new GridView(); 
      resultRepeater.DataSource = searchResultRows; 
      resultRepeater.DataBind(); 

      StringBuilder stringBuilder = new StringBuilder(); 
      System.IO.StringWriter textWriter = new System.IO.StringWriter(stringBuilder); 
      HtmlTextWriter htmlTextWriter = new HtmlTextWriter(textWriter); 
      resultRepeater.RenderControl(htmlTextWriter); 
      if (HttpContext.Current != null) 
      { 
       Page page = (Page)HttpContext.Current.Handler; 
       Label lbl = (Label)page.FindControl("lbl_test");//null 
       lbl.Text = searchResultRows[0].ToString();//exception 
      } 
      return stringBuilder.ToString(); 
     } 

我想更新現有的標籤lbl_test但我不能訪問標籤,設置它的價值,如何從頁面方法訪問服務器控件?

+2

沒辦法,你不能從頁面從一個WebMethod訪問任何東西,因爲頁面不通過生命週期其中它執行一系列處理步驟。這些包括初始化,實例化控件,恢復和維護狀態,運行事件處理程序代碼和呈現。 –

+0

簡而言之,你不能。 WebMethod是服務器端。 – Furtiro

+0

@TimSchmelter:非常感謝 –

回答

2

HTML

<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox> 
<input id="btnSearch" type="button" value="Search" 
    onclick = "GetSearchResult()" /> 
</div> 

的JavaScript:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script> 
<script type = "text/javascript"> 
function GetSearchResult() { 
    $.ajax({ 
     type: "POST", 
     url: "CS.aspx/GetSearchResult", 
     data: '{search: "' + $("#<%=txtSearch.ClientID%>")[0].value + '" }', 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: OnSuccess, 
     failure: function(response) { 
      alert(response.d); 
     } 
    }); 
} 
function OnSuccess(response) { 
    alert(response.d); 
} 
</script>