Returning Json instead of XML with Umbraco Base

混江龙づ霸主 提交于 2019-11-30 14:44:43

Here's a good example of how to return a JSON object with Umbraco Base:

/* Be sure to add References to:
 * 
 * umbraco.dll
 * System.Web.dll
 * System.Web.Extensions.dll
 */

using System.Web;
using System.Web.Script.Serialization;

using umbraco.presentation.umbracobase;

namespace CoB.Umb.Base.Example
{
    [RestExtension("Example")]
    public class Example
    {
        [RestExtensionMethod(returnXml = false, allowAll = true)]
        public static void Get()
        {
            string json = "";

            var person = new
            {
                firstName = "John",
                lastName = "Doe"
            };

            json = new JavaScriptSerializer().Serialize(person);

            HttpContext.Current.Response.ContentType = "application/json";
            HttpContext.Current.Response.Write(json);
        }
    }
}

And the javascript:

$.getJSON('/base/Example/Get', function (data) {
    alert("Hey, " + data.firstName + " " + data.lastName);
});

This site is amazing for helping with ASP.NET jQuery Ajax calls, this post in particular

Adrian Iftode is correct with his answer, but you don't need to set a response format on the server. If you ask for JSON the server will automatically encode to that. This is handy if you have multiple services calling the webservices and you need to encode differently for them.

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "WebService.asmx/WebMethodName",
  data: "{}",
  dataType: "json"
});

I also found this post helpful when I started to do this. It gives some code that moves all the $.ajax calls into one place.

// *** Service Calling Proxy Class
function serviceProxy(serviceUrl){
var _I = this;    this.serviceUrl = serviceUrl;     
// *** Call a wrapped object
    this.invoke = function(method,data,callback,error,bare)
    {
        // *** Convert input data into JSON - REQUIRES Json2.js
        var json = JSON2.stringify(data);
        // *** The service endpoint URL
        var url = _I.serviceUrl + method;
         $.ajax( {
                     url: url,
                    data: json,
                    type: "POST",
                    processData: false,
                    contentType: "application/json",
                    timeout: 10000,
                    dataType: "text",  // not "json" we'll parse
                    success:
                     function(res)
                     {
                         if (!callback) return;
                         // *** Use json library so we can fix up MS AJAX dates 
                         var result = JSON2.parse(res);
                         // *** Bare message IS result
                        if (bare)
                        { callback(result); return; }
                         // *** Wrapped message contains top level object node
                        // *** strip it off
                        for(var property in result)
                        {
                            callback( result[property] );
                            break;
                        }
                    },
                    error:  function(xhr) {
                        if (!error) return;
                        if (xhr.responseText)
                        {
                            var err = JSON2.parse(xhr.responseText);
                            if (err)
                                error(err);
                             else
                                error( { Message: "Unknown server error." })
                        }
                        return;
                    }
                });
       }} 
    // *** Create a static instance
    var Proxy = new serviceProxy("JsonStockService.svc/");
    // *** Call the webservice
    Proxy.invoke("GetStockQuote",{ symbol: symbol },function(result){...}, onPageError);

You might need to decorate the method to return Json

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
 public static string MemberRegister(int process)


complete(function( response ) {
   if (response.d == "success") {
     //
    }
}

edit

 jQuery.ajax({
                url: "/processform.aspx",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: $(this).serialize()

            })..
Rob Fyffe

Finally figured it out!

I needed to add "returnXml = false" to one of my class calls.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!