Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

asp.net - .NET AJAX Calls to ASMX or ASPX or ASHX?

What is the most efficient way of calling some business logic from javascript on the client side using AJAX? It looks like you can call a [WebMethod] on an aspx directly from javascript (in my case I'm using JQuery to help out) OR you can call a .asmx directly. Which call incurs less overhead? What is the best practice?

Also, what does the [ScriptService] attribute do on a class? I have never used this before on my .aspx [WebMethod] methods and everything seems to be working fine.

I'm hoping this is a purely objective question. Thanks in advance!

question from:https://stackoverflow.com/questions/673075/net-ajax-calls-to-asmx-or-aspx-or-ashx

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The ScriptService stuff in my opinion is a hidden gem in asp.net. Calls to the script service do not passback form data + viewstate, they are lean, fast JSON payloads.

Heres the best part, ASP.NET3.5's scriptmanager can do most of the work for you regarding generating a JS method for you to call and also setting up any JS classes needed.

A simple example for fetching details for a "Person", assuming Person is a C# class.

In PersonService.asmx:

namespace MyProj.Services {
  [System.Web.Script.Services.ScriptService]
  [System.Web.Script.Services.GenerateScriptType(typeof(Person))] 
  public class PersonService : System.Web.Services.WebService
  {
    [WebMethod, ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public Person GetPersonDetails(int id)
    { 
       /* return Logic here */
    }
  }
}

In DetailsPage.aspx

<asp:ScriptManager ID="ScriptManager1" runat="server">
 <Services>
  <asp:ServiceReference Path="~/Services/PersonService.asmx" />
 </Services>
</asp:ScriptManager>

By using a setup like this, you won't even need the help of JQuery to call the service and get back a JS version of your C# Person class, .net does that all for you. An example of using this service from JS would be:

MyProj.Services.PersonService.GetPersonDetails(id, _onDetailsCallbackSuccess, _requestFailed, null);

_onDetailsCallbackSuccess: function(result, userContext, methodName) {
 //all persons properties are now intact and available
 document.getElementById('txtFirstname').value = result.Firtname;
}

Anyway, it would be more then worth looking into the ASP.NET Ajax ScriptService stuff. Even if you decide not to use it this time it's a pretty wicked feature.

Links


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...