Ralph Lavelle
Ralph Lavelle

Reputation: 5769

Creating XML in C# for jQuery

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?

Upvotes: 1

Views: 1174

Answers (3)

Anon
Anon

Reputation: 11

You need to use theme="" example:

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

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1063328

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.

Upvotes: 3

Andrew Hare
Andrew Hare

Reputation: 351566

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

Upvotes: 0

Related Questions