首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >MVC:如何将字符串作为JSON返回

MVC:如何将字符串作为JSON返回
EN

Stack Overflow用户
提问于 2012-03-20 04:50:08
回答 4查看 116.7K关注 0票数 71

为了使进度报告过程更可靠,并使其与请求/响应分离,我在Windows服务中执行处理,并将预期的响应持久化到文件中。当客户端开始轮询更新时,目的是让控制器以JSON字符串的形式返回文件的内容。

该文件的内容被预序列化为JSON。这是为了确保响应过程中没有任何障碍。不需要进行任何处理(只需将文件内容读入字符串并返回)即可获得响应。

我最初认为这将是相当简单的,但事实并非如此。

目前我的控制器方法看起来是这样的:

控制器

已更新

[HttpPost]
public JsonResult UpdateBatchSearchMembers()
{
    string path = Properties.Settings.Default.ResponsePath;
    string returntext;
    if (!System.IO.File.Exists(path))
        returntext = Properties.Settings.Default.EmptyBatchSearchUpdate;
    else
        returntext = System.IO.File.ReadAllText(path);

    return this.Json(returntext);
}

Fiddler将此作为原始响应返回

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Mon, 19 Mar 2012 20:30:05 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 3.0
Cache-Control: private
Content-Type: application/json; charset=utf-8
Content-Length: 81
Connection: Close

"{\"StopPolling\":false,\"BatchSearchProgressReports\":[],\"MemberStatuses\":[]}"

AJAX

已更新

下面的内容可能会在以后更改,但现在,当我生成response类并像普通人一样将其作为JSON返回时,这是有效的。

this.CheckForUpdate = function () {
var parent = this;

if (this.BatchSearchId != null && WorkflowState.SelectedSearchList != "") {
    showAjaxLoader = false;
    if (progressPending != true) {
        progressPending = true;
        $.ajax({
            url: WorkflowState.UpdateBatchLink + "?SearchListID=" + WorkflowState.SelectedSearchList,
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            cache: false,
            success: function (data) {
                for (var i = 0; i < data.MemberStatuses.length; i++) {
                    var response = data.MemberStatuses[i];
                    parent.UpdateCellStatus(response);
                }
                if (data.StopPolling = true) {
                    parent.StopPullingForUpdates();
                }
                showAjaxLoader = true;
            }
        });
        progressPending = false;
    }
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9777731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档