javascript - 调用服务器方法,无需刷新页面

标签 javascript jquery asp.net ajax webforms

我读了很多关于此的文章和帖子,但我无法解决我的问题。

我在 aspx.cs 页面中有一些方法。方法不返回任何内容,它只是更改标签、文本框等中的值...

[System.Web.Services.WebMethod]
public void MethodName()
{
   //some code
}

在前端,我有一个单选按钮,应该调用此方法。当我调用重新加载页面的常规服务器端方法(rdbMethodName_CheckedChanged)时它起作用。现在我想调用这个方法而不重新加载。我尝试使用 Ajax

<asp:RadioButton ID="rbTwoSub" runat="server" GroupName="Subscription" value="2" AutoPostBack="false" OnCheckedChanged="rdbMethodName_CheckedChanged" />

为了调用 ajax 方法,我将 AutoPostBack 设置为 false 并创建 js 来调用它

$("#ctl00_PageContent_rbTwoSub").change(function () {
            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: "buy_sql_tools_new.aspx/MethodName?Product=ProductName",
                success: function (data) {
                    console.log('Success: ', data);
                },
                error: function (data) {
                    console.log('Error: ', error);
                }
            });
        });

此代码在控制台中返回没有参数且不调用此方法的页面的 html 代码。

我只需要调用后端方法来更改所有值,仅此而已。有谁知道如何做到这一点。

我只想一件事,那就是将所有 C# 代码重写为 javascript 代码,并在点击时仅调用 js 方法

--------编辑2015年12月16日

嗨,我尝试调用简单的 ajax post,它会返回单个值,但它也不起作用

下面是代码

            $.ajax({
                type: "POST",
                url: "buy_sql_tools_new.aspx/HelloWorld",
                data: "{}",
                contentType: "application/json",
                dataType: "json",
                success: function (msg) {
                    alert(msg);
                },
                error: function (msg) {
                    console.log('error' + msg);
                }
            });

aspx.cs

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string HelloWorld()
{
    return "Hello";
}

最佳答案

您的网络方法应该是静态的。另外,如果您想实际更改 ajax 调用成功后的某些内容,您将必须返回要更新的数据。

尝试做这样的事情。请注意,该示例使用 JSON.NET用于序列化。

jQuery 代码:

    $(document).ready(function () { 

        $("input:radio[name='Subscription']").click(function () {

            var selectedRadio = $("input:radio[name='Subscription']:checked").val();

            //Code to fetch complex datatype
            $.ajax({
                type: "POST",
                url: "buy_sql_tools_new.aspx/GetProduct?product=ProductName",
                dataType: "json",
                data: "{ id :'" + selectedRadio + "'}",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                  //perform the desired operations here eg. change labels and etc by getting the values from data object.
                },
                error: function () {
                    console.log('error');
                }
            });

        });            
    });
</script>

代码隐藏中的WebMethod:

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string GetProduct(string product)
    {
        string result = string.Empty;
        try
        {
            //Get the product
            Product product = new Product();
            product.Name = "Sql tool";
            product.Price = 3.99M;
            result = JsonConvert.SerializeObject(product);
            //example output
            //{
            //  "Name": "Apple",
            //  "Price": 3.99,
            //}
        }
        catch (Exception ex)
        {
             result = ex.ToString();
            //Exception Handling Logic goes here
        }
        return result;
    }

希望您觉得这有帮助。

关于javascript - 调用服务器方法,无需刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34240187/

相关文章:

c# - 无法加载文件或程序集 'Microsoft.ReportViewer.Common,版本 = 11.0.0.0

javascript - 如何适应高度为 :100% on iPhone 的 DIV

javascript - rollup.js 单次导入多次使用

javascript - 让节标题粘在包装器 div 的顶部

javascript - 如何制作从右到左的下拉菜单

javascript - 单击链接时防止 jquery fancybox 关闭

javascript - IE8之前内容不显示

javascript - jQuery 数组设置键和值并通过 AJAX 发送数组

asp.net - Response.Write 和 UpdatePanel

asp.net - 在 ASPxGridView 中获取 CheckBox.Checked 无法正常工作