我可以使用javascript调用服务器端方法而不会导致回发吗?

Pra*_*eta 1 javascript asp.net

我有JavaScript代码调用ASP.NET中的方法.基本上,我有一个SqlDataSource连接到一个GridView,我想改变它SelectCommandDataSource不会导致回发.

现在,我正在使用__dopostback方法,但正如我所说,我不希望页面重新加载.我只是想要GridView更新.这可能吗?

Ica*_*rus 6

那不是怎么做的.有很多方法,但最简单的方法是将您的内容包含在UpdatePanel中并在页面上删除ScriptManager.

例如:

<asp:ScriptManager id="mymanager" runat="server" />

<asp:UpdatePanel id="mainPanel" runat="server">
<ContentTemplate>

<! -- Put your content here -->

</ContentTemplate>
</asp:UpdatePanel>
Run Code Online (Sandbox Code Playgroud)

现在,您网页上的所有互动都将通过Ajax完成.

更好的方法(我目前使用的方法)

使用jQuery与Web服务一起进行Ajax调用.

示例代码:

[System.Web.Script.Services.ScriptService]
public class MyWebService: System.Web.Services.WebService
{
    [WebMethod]
    public List<BusinessObject> GetSomeData(int dataID)
    {
        //Invoke your business layer and get some data here
        List<BusinessObject> result = BusinessLayer.GetSomeData();
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

在客户端使用jQuery,你可以这样做:

$.ajax({
    type: "POST",
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    url: "MyWebService.svc/GetSomeData",
    data: {'dataId': you_id_here },
    success: function(result) {
        //result.d will contain an array of BusinessObject in JSON format
        //You can iterate through this list and populate your html using this data.
        //You can either use jQuery templates
        //or one of the many jQuery plugins for tabular data.
        //I use datatables:
        //http://datatables.net/
        for(int i=0;i<result.d.length; i++)
        {
            //do something here if you want to iterate one by one constructing your
            //html
        }
    },
    error: function(xhr, ajaxOptions, thrownError) {
           //display error here
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

我强烈建议您查看以下链接:

  1. http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
  2. http://encosia.com/simplify-calling-asp-net-ajax-services-from-jquery/