Anyname Donotcare Anyname Donotcare - 4 months ago 13
Ajax Question

How to access server controls from page methods?

If i use a page method like this :

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





I want to update my existing label
lbl_test
but i can't access the label to set it's value ,How to access server controls from page methods ?

Answer

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>