Reputation: 3562
Within a web form I have the following jQuery setup to call a method in my code behind file.
<script src="js/jquery-1.7.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#newBtn").click(function () {
$.ajax({
type: "POST",
url: "AJAXCaller.aspx/GetTimer",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false
});
return false;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<a href="#" class="link1" runat="server">Click here</a><br /><br />
<asp:LinkButton ID="newBtn" runat="server" Text="ASP Link" />
<asp:Label ID="time_lbl" runat="server" />
</div>
</form>
</body>
And within the code behind I have the following:
[WebMethod]
public void GetTimer()
{
time_lbl.Text = DateTime.Now.ToString();
}
I realize this currently does not work in the current syntax.
I've been able to access the method if I set it to static however I don't want to just return a string or single value. I want to access a method that in turn access a web service to return a collection of data.
I would like to know if it is possible to perform something like this where I can call a method and have it update a field in the UI such as the above method where when called the server side script would to the ui a value for the date field?
Thanks in advance for any suggestions.
Upvotes: 3
Views: 11198
Reputation: 69905
It is not at all possible because you cannot update any field on UI from server side.
Instead of using WebMethod
in aspx page use Asp.Net webservices instead to write web methods which can be called using ajax
.
ajax
method has a success callback where you can grab the service response and then update the UI field by accessing it with appropriate selector.
E.g
$(function () {
$("#newBtn").click(function () {
$.ajax({
type: "POST",
url: "AJAXCaller.asmx/GetTimer",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(data){
$("#ClientIdOftime_lbl").text(data);
}
});
return false;
});
});
Upvotes: 2