开发者

How do I pass Json data back to the client from a standard ASP.NET WebForm using the Response object?

I'm trying to return simple Json data back from a standard WebForm. It sounds very dumb, but I actually need this to happen. I'm using MVC, and this is one of only 3 pages that I use that is NOT an MVC view. Otherwise, I'd write a controller to return Json(myData), but I can't do that.

Here is what I'm doing:

        var serializ开发者_开发技巧er = new JavaScriptSerializer();
        var json = serializer.Serialize(someObject);
        HttpContext.Current.Response.ContentType = "application/json";
        HttpContext.Current.Response.Write(json);
        HttpContext.Current.Response.End();

However, I keep getting a browser dialog asking me to do with the webpage, meaning it's trying to download the page... ?

What am I missing?

My Solution...

I was able to solve the problem by changing my ContentType to "text/html" (yes even though it's Json data). :( While it's not the correct approach, it works for me, as there is only Mvc view in my entire solution that will ever call it.


i have checked your code and its correct. Actually the response type is application/json and the browser tries to open a dialog box to open it in some application. If you send an ajax request, you can able to get response, parse and show data through javascript.


The most important question is what do you want to do with the data. If you just pass it like a result of a page request, it is quite normal that the browser doesn't know what to do with it. If you want to process it in some way, you have to hook it up somewhere (an asynchronous request that updates something at the page ?).

Anyway, if you just want to use a page to return data it's probably better to use HttpHandler (file with extension ashx) instead, it's a more lightweight alternative when you don't need all the rendering lifecycle that the usual WebForm has to do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜