无法从.net中的JSON响应中删除.d封装

时间:2014-08-12 08:04:20

标签: c# jquery asp.net ajax json

即使在伟大的博客文章Never worry about ASP.NET AJAX’s .d again之后,我也无法逃避JSON响应中的.d封装。我不知道我做错了什么,所以我会复制我的服务器端和客户端代码。

我使用Newtonsoft.JSON库序列化JSON。

客户机侧:

<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>

了Serverside

    [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;
    }

Serverside - Update 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();
    }
}

1 个答案:

答案 0 :(得分:13)

尝试使用void方法而不返回。而是将输出写入自己的响应!

  [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();
   }

最后保持这两个电话非常重要:

flush:确保输出写入流

结束:结束流以防止asp.Net将空Json写入流