我想通过 ajax 调用来调用 Web 表单中的 Web 方法函数,该调用会更新名为“First”的分区中文本框的值,而无需刷新整个页面,而仅刷新那些文本框或分区。我的 ASP.NET 代码包含带有 jQuery 的 ajax,如下所示:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="test_with_ajax.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="First" style="margin-left:45%">
<asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
<br />
<br />
<asp:TextBox ID="TextBoxID" runat="server"></asp:TextBox>
</div>
<br />
<div id="Second" style="margin-left:50%">
<asp:Button ID="ShowButton" runat="server" Text="Show"/>
</div>
<asp:ScriptManager ID="ScriptManager" runat="server" EnableCdn="true" AjaxFrameworkMode="Disabled">
<Scripts>
<asp:ScriptReference Path="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"/>
</Scripts>
</asp:ScriptManager>
<script>
var pageurl = '<%=ResolveUrl("~/WebForm1.aspx/Show()") %>';
$('document').ready
(
function () {
$("#ShowButton").click
(
function (e) {
e.preventDefault();
$.ajax
(
{
type: 'POST',
URL: pageurl,
async: "true",
success: function (x) {
alert("Done Successfully with " + x.msg);
},
error: function (e) { alert("The call got failed due to " + e.msg); }
}
);
//$("#First").html("").append(data);
}
);
}
)
</script>
</form>
</body>
</html>
我的 webform 类包含正在调用的函数:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace test_with_ajax
{
public partial class WebForm1 : System.Web.UI.Page
{
[WebMethod]
public static void Show()
{
WebForm1 t = new WebForm1();
t.TextBoxName.Text = "Sarthak";
t.TextBoxID.Text = "66";
}
}
}
但我没有得到我想要的结果。它显示 ajax 调用成功部分的警报消息,但根本不更新文本框。
最佳答案
This is not the right way of updating your textboxes because you are creating new object of webform and assiging values to textboxes. You should return data from webmethod and update textboxes in javascript code.Also add datatype in your ajax call.
尝试这样
[WebMethod]
public static string Show()
{
return "Hello world";
}
比在你的ajax成功中这样写
success: function (x) {
alert("Done Successfully with " + x.msg);
$('#TextBoxName').val(x.d);
},
这只是一个字符串,您可以根据需要返回数组、列表或对象。
关于javascript - ajax 调用方法来更新更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27394907/