无刷新页面调用服务器方法 [英] Call server method without refresh page

查看:125
本文介绍了无刷新页面调用服务器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读这个很多文章和帖子,但我不能昏为解决我的问题。

我在aspx.cs页面的一些方法。方法不返回任何东西,它只是改变标签值,文本框,...

  [System.Web.Services.WebMethod]
公共无效的方法名()
{
   //一些code
}

在前端我有单选按钮,应该调用此方法。当我打电话常规服务器端方法(rdbMethodName_CheckedChanged),它重新加载页面。它的工作。现在我想调用此方法无需重新加载。我试着全光照的Ajax

 < ASP:单选按钮ID =rbTwoSub=服务器组名=订阅VALUE =2的AutoPostBack =假OnCheckedChanged =rdbMethodName_CheckedChanged/>

要AJAX调用的方法我设置的AutoPostBack为false,并为JS调用它

  $(#ctl00_PageContent_rbTwoSub)。改变(函数(){
            $阿贾克斯({
                键入:GET,
                的contentType:应用/ JSON的;字符集= UTF-8,
                网址:buy_sql_tools_new.aspx /方法名产品=产品名称,
                成功:功能(数据){
                    的console.log('成功:',数据);
                },
                错误:功能(数据){
                    的console.log('错误:',错误);
                }
            });
        });

在控制台控制台HTML code本code换取页面而不paramenter,不调用此方法。

我只需要调用后端方法,它会改变所有的值,仅此而已。有没有人有一些想法如何做到这一点。

只有一件事我有主意,那就是重写所有C#code到JavaScript的code,并呼吁只有在点击JS方法

- - 的 - - 的 - - 的 - - 的编辑二○一五年十二月一十六日

您好,我试着打简单的Ajax后,将返回我的一个值,但它也不能正常工作

这里是code以下

  $阿贾克斯({
                键入:POST,
                网址:buy_sql_tools_new.aspx / HelloWorld的,
                数据:{},
                的contentType:应用/ JSON
                数据类型:JSON
                成功:函数(MSG){
                    警报(MSG);
                },
                错误:函数(MSG){
                    的console.log('错误'+味精);
                }
            });

aspx.cs

  [的WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)
公共静态字符串的HelloWorld()
{
    返回你好;
}


解决方案

您的WebMethod应该是静态的。此外,如果你想真正的AJAX调用成功改变一些东西,你将不得不返回,你将更新数据。

试着做这样的事情。注意例子是使用 JSON.NET 进行序列化。

jQuery的code:

  $(文件)。就绪(函数(){        $(输入:无线​​电[名称='订阅'])点击(函数(){。            。VAR selectedRadio = $(输入:无线​​电[名称='订阅']:勾选)VAL();            // code获取复杂的数据类型
            $阿贾克斯({
                键入:POST,
                网址:buy_sql_tools_new.aspx / GetProduct产品=产品名称,
                数据类型:JSON
                数据:{ID:'+ selectedRadio +'},
                的contentType:应用/ JSON的;字符集= UTF-8,
                成功:功能(数据){
                  //此处如执行所需的操作。从数据对象获得的值更改标签等。
                },
                错误:函数(){
                    的console.log('错误');
                }
            });        });
    });
< / SCRIPT>

的WebMethod在codebehind:

  [的WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)
    公共静态字符串GetProduct(串产品)
    {
        字符串结果=的String.Empty;
        尝试
        {
            //获取产品
            产品产品=新产品();
            product.Name =SQL工具;
            product.Price = 3.99M;
            结果= JsonConvert.SerializeObject(产品);
            //输出示例
            // {
            //名:苹果
            //价格:3.99,
            //}
        }
        赶上(异常前)
        {
             结果= ex.ToString();
            //异常处理逻辑放在这里
        }
        返回结果;
    }

希望对您有所帮助。

I was reading a lot articles and posts about this but I couldn't faint solution for my problem.

I have some method in aspx.cs page. Method doesn't return anything, it just change value in labels, text boxes,...

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

On frontend I have radio button which should call this method. It work when I call regular server side method (rdbMethodName_CheckedChanged) which reload page. Now I'd like to call this method without reload. I tried usin Ajax

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

To call ajax method I set AutoPostBack to false and create js for call it

$("#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);
                }
            });
        });

This code return in console console html code for page without paramenter and without calling this method.

I need just to call backend method which going to change all values and that's it. Does anyone have some idea how to do this.

Only one thing more I have on mind and that is to rewrite all C# code to javascript code and to call only js methods on clicks

-------- Edit 12/16/2015

Hi, I tried to call simple ajax post which will return me single value but it also don't work

here is code below

            $.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";
}

解决方案

Your webmethod should be static. Also if you want to actually change something on the success of the ajax call you will have to return the data that you will be updating.

Try doing something like this. Note the example is using JSON.NET for serialization.

jQuery code:

    $(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 in the codebehind:

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

Hope you find this helpful.

这篇关于无刷新页面调用服务器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆