简体   繁体   English

如何使用Response对象将Json数据从标准ASP.NET WebForm传递回客户端?

[英]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. 我正在尝试从标准WebForm返回简单的Json数据。 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. 我正在使用MVC,这是我使用的仅有3页的页面之一,而不是MVC视图。 Otherwise, I'd write a controller to return Json(myData), but I can't do that. 否则,我将编写一个控制器以返回Json(myData),但我无法做到这一点。

Here is what I'm doing: 这是我在做什么:

        var serializer = 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). 通过将ContentType更改为“ text / html” (即使是Json数据也可以),我能够解决该问题。 :( 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. :(尽管这不是正确的方法,但是它对我有用,因为在我的整个解决方案中只有Mvc视图可以调用它。

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. 实际上,响应类型为application / json ,浏览器尝试打开一个对话框以在某些应用程序中将其打开。 If you send an ajax request, you can able to get response, parse and show data through javascript. 如果发送ajax请求,则可以通过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. 无论如何,如果只想使用页面返回数据,则最好使用HttpHandler(扩展名为ashx的文件),当您不需要通常的WebForm必须执行的所有渲染生命周期时,这是一种更轻量级的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM