Using the ASP.NET AJAX ScriptMethodAttribute to Return XML Data

Web Services provide a convenient way to pass data between AJAX applications and a server.  ASP.NET AJAX provides an excellent infrastructure for Web Service integration into AJAX applications and makes it all cross-browser through incorporating JSON into the mix.  While JSON is compact and a very good fit for AJAX applications, there may be times where it's easier or more convenient to pass back raw XML to an AJAX client for processing.  This is especially true if the browser provides robust XML parsing APIs like Internet Explorer 5+.  For example, you may have a Web Service that obtains RSS data and returns it as an XmlDocument or XmlElement object.

Switching between JSON and XML response messages is accomplished by using the ASP.NET AJAX Extensions's ScriptMethodAttribute.  It can be used to specify the response type of a given Web Method and even control if the method accepts GET requests (POST is the default which is good given the existence of CSRF attacks). 

An example of using the ScriptMethodAttribute class to return XML data from a Web Method is shown next.  You'll see that the ResponseFormat property is set to ResponseFormat.Xml instead of ResponseFormat.Json.  Keep in mind that this is really only useful if the browser supports XML parsing, which means it may be most applicable in Intranet scenarios where a standard browser such as IE is used throughout a company.

[ScriptMethod(ResponseFormat ResponseFormat.Xml)]
[WebMethod]
public XmlElement GetRssFeed(string url)
{
    XmlDocument doc 
= new XmlDocument();
    
doc.Load(url);
    return 
doc.DocumentElement;
}

The following code demonstrates how to call the GetRssFeed() Web Method and parse the returned XML data using Internet Explorer's XML parsing APIs:

<script type="text/javascript">
    
function GetRss()
    {
        InterfaceTraining.DemoService.GetRssFeed(
"http://blogs.interfacett.com/dan-wahlins-blog/rss.xml",OnWSRequestComplete);
    
}

    
function OnWSRequestComplete(result)
    {                
        
if (document.all) //Basic way (very basic) to check for IE DOM
        
{
            
var items result.selectNodes("//item");
            for 
(var i=0;i<items.length;i++)
            {
                
var title items[i].selectSingleNode("title").text;
                var 
href items[i].selectSingleNode("link").text;
                
$get("divOutput").innerHTML +
                   
"<a href='" + href + "'>" + title + "</a><br />";
            
}
        } 
else
        
{
            $
get("divOutput").innerHTML "RSS not available in this browser.";
        
}
    }
   
</script>

comments powered by Disqus

No Comments