views:

56

answers:

4

I am trying to use jQuery .load() to get straight html from a asmx web service:

$('#target').load('MyService.asmx/GetHtml');

In .NET code, GetHtml() returns as string:

    [WebMethod(EnableSession = false)]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Xml)]
    public string GetHtml()
    {
        return "<span>Hi</span>";
    }

That returns:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/"&gt;&amp;lt;span&amp;gt;Hi&amp;lt;/span&amp;gt;&lt;/string&gt;

Notice that the string is encoded. With that encoding, $.load doesn't work right. The displayed text actually has the tags shown.

How can I get the WebMethod call to return just this?

<span>Hi</span>
+6  A: 

How about this:

Instead of pulling HTML from the service, pull data, then use jquery to insert that data into the DOM.

Then you won't have to XML decode your HTML.

Randolpho
I don't think I would have thought of that. Thank you. I am going with @Andrew's suggestion in that it allows me to use the simple .load() call.
slolife
+2  A: 

I'm pretty sure that if you want straight HTML back from a service, you would need to use a handler (.ashx) rather than .asmx. I don't know of a way to get .asmx not to encode your data in some format (though you can change what that format is.

That said, @Randolpho also has a good point.

Andrew
A: 

The simplest way is to not use a web service at all. An HTTP request with a response containing HTML is basically the most common operation that happens on the web so the default tools are designed to do that. In the case of asp.net that would be an aspx file.

Jake T.
+1  A: 

The short answer (as other posters have suggested) is: don't do that. Return JSON and use JS to craft it into the desired HTML. See this discussion for more details/comments.

However, if you have no choice but to return HTML (maybe your project mgr/architect is afraid of true webservice design, for some reason), I agree with Jake T's answer here: use ajax to call an ASPX page.

ASPX's whole purpose in life is to return HTML (unlike ASMX or ASHX). Most importantly, well-written ASPX separates the HTML from the logic/codebehind. That way, when you need to change the HTML from a list to a table (or whatever) you can do so without re-compiling, re-testing, and re-deploying the whole darn system! :)

mikemanne
My objective here is to not create a ton of HTML inside of javascript. Makes designing and laying things out a real pain. What I am doing is creating a few ASCX UserControls that create the specific HTML when requested. I use some code to render the user control into a string and return that. Per @Andrew's suggestion, I am using a handler instead of a webservice. I had already gone down the path of using a webservice to return just data to the browser and using javascript to loop through that data to clone and create html.
slolife