代码之家  ›  专栏  ›  技术社区  ›  camainc

如何在浏览器不提示保存文件的情况下返回JSONResult?

  •  0
  • camainc  · 技术社区  · 16 年前

    编辑:我早就超越了VS2008,使用MVC 3+返回JSON结果没有任何问题。我想把这个问题标为过时的,或是类似的东西。也许有人仍然会从中发现价值,并给出答案,但我不能标记为“正确”,因为我没有办法测试他们。

    我是MVC的新手,我正试图让一个简单的网站工作。我开始怀疑它是否真的值得…我本可以让这个网站运行“老派”的ASP.Net两到三次…但这不是重点;-)

    如果浏览器不提示我将响应保存为文件,我如何让控制器返回JSONResult?下面是调用该操作的JavaScript:

    $("select#PageId").change(function() {
        var id = $("#PageId > option:selected").attr("value");
        $.getJSON('FindCategories/', { PageId: id }, 
            function(data) {
                if (data.length > 0) {
                    var options = '';
                    for (c in data) {
                        var cat = data[c];
                        options += "<option value='" + cat.CategoryId + "'>" + cat.CategoryName + "</option>";
                    }
                    $("#CategoryId").removeAttr('disabled').html(options);
                } else {
                    $("#CategoryId").attr('disabled', true).html('');
                }
        });
    });
    

    这是我的控制器操作:

    Function GetCategoriesByPage(ByVal PageId As Integer) As JsonResult
    
        Dim categories As List(Of Models.WebCategoryLite) = _service.ListCategoriesByPageId(PageId)
    
        Dim res As New JsonResult
        res.Data = categories
        Return res
    
    End Function
    

    Fiddler告诉我JSON正在返回到浏览器:

    HTTP/1.1 200 OK
    Server: ASP.NET Development Server/9.0.0.0
    Date: Mon, 24 Aug 2009 19:43:53 GMT
    X-AspNet-Version: 2.0.50727
    X-AspNetMvc-Version: 1.0
    Cache-Control: private
    Content-Type: application/json; charset=utf-8
    Content-Length: 246
    Connection: Close
    
    [{"CategoryID":1,"CategoryName":"Sample Category"},{"CategoryID":2,"CategoryName":"Another Sample"},{"CategoryID":3,"CategoryName":"Yet Another Sample"}]
    

    不管我用什么浏览器,我都会得到一个“另存文件为”的提示。

    我在visualstudio2008ide中运行这个。无论是在IDE还是在IIS中,我都需要做些什么才能使此工作正常进行?

    提前谢谢!

    2 回复  |  直到 13 年前
        1
  •  3
  •   Cleiton    16 年前

    只需将内容类型设置为“文本/纯文本”:

    Function GetCategoriesByPage(ByVal PageId As Integer) As JsonResult
    
        Dim categories As List(Of Models.WebCategoryLite) = _service.ListCategoriesByPageId(PageId)
    
        Dim res As New JsonResult
        res.Data = categories
        res.ContentType = "text/plain"
        Return res
    
    End Function
    

    如果它不起作用,你可以子类化 JsonResult公司 和覆盖 执行人 方法:

    public class myOwnJsonResul: JsonResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            base.ExecuteResult(context);
            context.HttpContext.Response.ContentType = "text/plain";
        }
    }
    
        2
  •  1
  •   Sergey Glotov Nitesh Khosla    13 年前

    干得好。

    var s = new JsonResult();
    s.ContentType = "text/plain";
    s.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    s.Data = AreaServiceClient.GetCityList(id);            
    return s;
    
    推荐文章