如何使用 jQuery 从 ASP.NET 代码后面调用非静态方法
在 Web 表单中,我有以下 jQuery 设置来调用代码隐藏文件中的方法。
<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>
在后面的代码中,我有以下内容:
[WebMethod]
public void GetTimer()
{
time_lbl.Text = DateTime.Now.ToString();
}
我意识到这目前在当前语法中不起作用。
如果我将其设置为静态,我就可以访问该方法,但我不想只返回字符串或单个值。我想访问一个方法,该方法又访问 Web 服务以返回数据集合。
我想知道是否可以执行类似的操作,我可以调用一个方法并让它更新 UI 中的字段,例如上面的方法,当调用服务器端脚本时,它会向 ui 传递一个日期值场地?
预先感谢您的任何建议。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是根本不可能的,因为您无法从服务器端更新 UI 上的任何字段。
不要在 aspx 页面中使用
WebMethod
,而是使用 Asp.Net Webservices 来编写可以使用ajax
调用的 Web 方法。ajax
方法有一个成功回调,您可以在其中获取服务响应,然后通过使用适当的选择器访问它来更新 UI 字段。例如
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 usingajax
.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