views:

251

answers:

3

I'm trying to generate some XML for a jQuery.get (AJAX) call, and I'm getting the following error from my C# page: "Using themed css files requires a header control on the page. (e.g. <head runat="server" />)."

The file generating the XML is a simple .aspx file, consisting entirely of:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ChangePeopleService.aspx.cs" Inherits="ChangeRegister.Person.ChangePeopleService" EnableTheming="false" %>

with codebehind using Linq-to-XML, which is working ok:

XElement xml =  new XElement("People",
                from p in People
                select new XElement("Person", new XAttribute("Id", p.Id),
                                    new XElement("FirstName", p.FirstName)));

HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.Write(xml.ToString());

I know that the error relates to the Web.Config's <pages styleSheetTheme="default" theme="default"> tag, because when I remove the 'styleSheetTheme' and 'theme' attributes, the XML gets generated ok. The problem then obviously is that every other page loses its styling. All this leads me to think that I'm approaching this wrong.

My question is: what's an accepted way to generate XML in C#, for consumption by a jQuery AJAX call, say?

A: 

Try writing to the Response.OutputStream instead:

HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;

using (TextWriter textWriter 
    = new StreamWriter(HttpContext.Current.Response.OutputStream, Encoding.UTF8))
{
    XmlTextWriter writer = new XmlTextWriter(textWriter);
    writer.WriteString(xml.ToString());
}
Andrew Hare
That didn't seem to make any difference Andrew :-( Thanks though
Rafe Lavelle
+3  A: 

If I am returning simple data (not a page), I probably wouldn't use aspx; that is really web-forms, but what you are returning isn't a web-form. Two options leap to mind:

  • use ASP.NET MVC; sounds corny, but it really is geared up to return different types of response much more elegantly
  • use a handler (ashx) - which omits all the web-form noise, just leaving you with a HttpContext with which to construct your response

You could also try (within aspx) clearing the response (Clear()?) and calling Close() afterwards. But IMO a lot more roundabout than just using a handler.

Marc Gravell
See also: http://stackoverflow.com/questions/878695/how-to-return-an-xml-string-as-an-action-result-in-mvc
Marc Gravell
I used the 'ashx' option, not having MVC-enabled my site, and that seems to have done the trick, thanks Marc
Rafe Lavelle
A: 

You need to use theme="" example: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ChangePeopleService.aspx.cs" Inherits="ChangeRegister.Person.ChangePeopleService" Theme="" %>

Anon