无法从.net的JSON响应中删除.d封装 [英] Can't remove .d encapsulation from JSON response in .net

查看:65
本文介绍了无法从.net的JSON响应中删除.d封装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使在出色的博客文章也不必担心ASP. NET AJAX的.d再次我无法在JSON响应中转义.d封装.我不知道我做错了什么,所以我将同时复制服务器端代码和客户端代码.

Even after the great blog post Never worry about ASP.NET AJAX’s .d again I can't escape the .d encapsulation in my JSON response. I don't know if I'm doing something wrong so I'll copy both my serverside and clientside code.

我正在使用Newtonsoft.JSON库序列化JSON.

I'm serializing JSON using Newtonsoft.JSON library.

客户端:

<script type="text/javascript">
$(function () {
    $("#bt").click(function () {
        $.ajax({
            type: "POST",
            url: "<%= Page.ResolveUrl("~/MapView.aspx/GetLocations")%>",
            data: "{ type: '<%= Page.RouteData.Values["type"].ToString() %>', id: '<%= Page.RouteData.Values["id"].ToString() %>' }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            dataFilter: function(data) {
                var msg;

                if (typeof (JSON) !== 'undefined' && 
                    typeof (JSON.parse) === 'function')
                    msg = JSON.parse(data);
                else
                    msg = eval('(' + data + ')');

                if (msg.hasOwnProperty('d'))
                    return msg.d;
                else
                    return msg;
            },
            success: function (msg) {
                console.log(msg);
            },
        });
    });
});
</script>

服务器端

    [System.Web.Services.WebMethod]
    public static string GetLocations(int id, string type)
    {
        string data = "";


        if (type == "attraction")
        {
            var attractions = db.Attraction
                                .Where(a => a.AttractionId == id)
                                .Select(p => new { p.AttractionId, p.Name, p.Description, p.Location })
                                .ToList();


            JObject attractionsJSON = new JObject(
                new JProperty("Attractions", new JArray(
                    from a in attractions
                    select new JObject(
                        new JProperty("id", a.AttractionId),
                        new JProperty("name", a.Name),
                        new JProperty("location", a.Location),
                        new JProperty("description", a.Description)
                        ))));

            data = attractionsJSON.ToString();
        }
        else if (type == "category")
        {
            var attractions = db.Attraction

                .Select(p => new { p.AttractionId, p.Name, p.Description, p.Location, p.CategoryId })
                .ToList();

            if (id != 0)
            {
                attractions = attractions.Where(a => a.CategoryId == id)
                    .ToList();
            }


            JObject attractionsJSON = new JObject(
                new JProperty("Attractions", new JArray(
                    from a in attractions
                    select new JObject(
                        new JProperty("id", a.AttractionId),
                        new JProperty("name", a.Name),
                        new JProperty("location", a.Location),
                        new JProperty("description", a.Description)
                        ))));

            data = attractionsJSON.ToString();

        }
        return data;
    }

服务器端-更新1

    [System.Web.Services.WebMethod]
    public static void GetLocations(int id, string type)
    {
        string data = "";


        if (type == "attraction")
        {
            var attractions = db.Attraction
                                .Where(a => a.AttractionId == id)
                                .Select(p => new { p.AttractionId, p.Name, p.Description, p.Location })
                                .ToList();


            JArray attractionsJSON = new JArray(
                    from a in attractions
                    select new JObject(
                        new JProperty("id", a.AttractionId),
                        new JProperty("name", a.Name),
                        new JProperty("location", a.Location),
                        new JProperty("description", a.Description)
                        ));

            data = attractionsJSON.ToString();
        }
        else if (type == "category")
        {
            var attractions = db.Attraction

                .Select(p => new { p.AttractionId, p.Name, p.Description, p.Location, p.CategoryId })
                .ToList();

            if (id != 0)
            {
                attractions = attractions.Where(a => a.CategoryId == id)
                    .ToList();
            }


            JArray attractionsJSON = new JArray(
                    from a in attractions
                    select new JObject(
                        new JProperty("id", a.AttractionId),
                        new JProperty("name", a.Name),
                        new JProperty("location", a.Location),
                        new JProperty("description", a.Description)
                        ));

            data = attractionsJSON.ToString();

        }


        var js = new System.Web.Script.Serialization.JavaScriptSerializer();

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
        HttpContext.Current.Response.Write(js.Serialize(data));
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
    }
}

推荐答案

尝试使用无返回值的void方法.而是写输出以自己回应!

try using void method with no return. instead write the output to response yourself!

  [System.Web.Services.WebMethod]
    public static void GetLocations(int id, string type)
    {
     // var attractions = something ;

     var js = new System.Web.Script.Serialization.JavaScriptSerializer();

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
        HttpContext.Current.Response.Write(  js.Serialize(attractions )  );
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
   }

非常重要的是将这两个通话结束:

Very important to keep these 2 calls at end:

flush:确保将输出写入流

flush : makes sure output is written to stream

End:结束流,以防止asp.Net将空的Json写入流中

End : ends the stream to prevent asp.Net from writing empty Json to stream

这篇关于无法从.net的JSON响应中删除.d封装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆