Get response from aspx page in json format instead of plain html
I want to make an ajax call to the server. I need to get the html of a page like foo.aspx: Foo.aspx html:
<form>
<div>foo</div>
</form>
I am calling this page from a remote page, for example:
$.ajax({
url: '/foo.aspx',
data: {},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
}
});
I need the html of this page, but my requirement is that the response from this page must be in JSON format. i.e.
{"myresponse": {
"id": "123",
"html":<HTML of foo.aspx>,
}}
I need html as a json property because I need to set other properties as well from the foo.aspx code? How can I get the response in the aspx page in json format instead of plain html? What is the other approach for getting the HTML of the remote page + other properties in json format from the server? Should I go for HTTPHandlers? If so, how can I get the html foo.aspx in this HTTPHandler?
source to share
You can try overriding how your page is rendered:
protected override void Render(HtmlTextWriter writer)
{
var sw = new System.IO.StringWriter();
var tw = new HtmlTextWriter(sw);
base.Render(tw);
Response.Write(String.Format("{{\"myresponse\": {{ \"id": \"123",\"html\":\"{0}\"}}}}"
, Server.HtmlEncode(sw.ToString()).Replace("\n"," "));
Response.Flush();
Response.End();
}
Sorry for any syntax error and basic handling of carriage returns. I think it would be better to buffer the output during page_load (Response.BufferOutput = true)
source to share
Basically, you need to create an HTTPHandler that wraps up the output of Foo.aspx to your JSON evenlope. HAve said the JS call would be to url / MyWebHandler? Page = foo.aspx instead of just /foo.aspx. Inside the handler, all you need to do is simply request your page and dump its output.
source to share
I modified jbl's example of overriding the Render method a bit, it worked great for me. I don't need HTML coding, just need to apply some formatting and include content type
protected override void Render(HtmlTextWriter writer)
{
var sw = new System.IO.StringWriter();
var tw = new HtmlTextWriter(sw);
base.Render(tw);
var html = sw.ToString();
html = html.Replace("\n", " ");
html = html.Replace("\r", " ");
html = html.Replace("\t", " ");
var data = html.Replace("\"", "\\\"");
data = data.Replace("/", "\\/");
var json = String.Format("{{\"html\":\"{0}\"}}", data);
Response.ContentType = "application/json";
Response.Write(json);
Response.Flush();
Response.End();
}
source to share