5

I have a .NET method that adds a new member to my DB. It does this through an AJAX request. I have this working correctly, however I am having problems returning the correct response message so I can print the correct messages to the user.

My method at the moment looks like this:

    public static string MemberRegister(int process)
    {

        //here we find form values posted to the current page
        HttpRequest post = HttpContext.Current.Request;

        //get values from ajax URL
        var name = post["name"];
        var email = post["email"];
        var username = post["username"];
        var password = post["password"];

        //check if email exists
        if (Member.GetMemberFromEmail(email) == null)
        {

            MemberType userMemberType = new MemberType(1111); //id of membertype 'demo'
            Member newMember = Member.MakeNew(name, userMemberType, new umbraco.BusinessLogic.User(0));

            newMember.AddGroup(MemberGroup.GetByName("Active").Id);
            newMember.Email = email;
            newMember.Password = password;
            newMember.LoginName = username;

            newMember.Save();

            return "success";
        }
        else
        {
            return "emailError";
        }        

    }

My Ajax code looks like:

        // submit
    $registerForm.submit(function() {

            $loader.show();

            jQuery.ajax({
                url: "/processform.aspx",
                type: "POST",
                data: $(this).serialize()

            }).complete(function( response ) {

            alert(response.responseText);

                if( response.responseText === "success" ) {
                    $registerSuccess.fadeIn(); 
                } elseif( response.responseText === "emailError" ) {
                    $registerEmailError.fadeIn(); 
                } else {
                    $registerError.slideDown();                        
                }

                $loader.hide();

            });



            return false;

    });

For example if the member all ready exists it returns the reponse:

<value>emailError</value> 

I just want it to return emailError not the value tags as well. How do I do this?

Fiddler (Raw):

 HTTP/1.1 200 OK
 Content-Type: text/xml; charset=utf-8
 Vary: Accept-Encoding
 Server: Microsoft-IIS/7.5
 X-Powered-By: ASP.NET
 Date: Sun, 25 Mar 2012 20:59:54 GMT
 Content-Length: 25

 <value>emailError</value>


    POST http://domain.com/base/Forms/MemberRegister/process.aspx HTTP/1.1
    Host: domain.com
    Connection: keep-alive
    Content-Length: 125
    Origin: http://domain.com
    X-Requested-With: XMLHttpRequest
    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11
    Content-Type: application/json; charset=UTF-8
    Accept: application/json, text/javascript, */*; q=0.01
    Referer: http://domain/register.aspx
    Accept-Encoding: gzip,deflate,sdch
    Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
    Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
    Cookie: ASP.NET_SessionId=ys4mmhsn2mpqcpja1iyjg04m; UMB_UPDCHK=1; __utma=256732567.15732944.1331581910.1332617890.1332627641.11; __utmc=256732567; __utmz=256732567.1331581910.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); UMB_UCONTEXT=12621b40-16fe-4422-a027-cf4fa68fe03d; __utma=176230262.1311679778.1332368941.1332694687.1332708163.12; __utmb=176230262.3.10.1332708163; __utmc=176230262; __utmz=176230262.1332368941.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)

    __VIEWSTATE=%2FwEPDwUENTM4MWRkEytUM47m6NUA6dpfOudOh9t51j6okfG%2BQhu4Em%2B26KU%3D&name=ppp&email=ppp&username=ppp&username=ppp

Thanks Robert

4 Answers 4

9

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);
});
4
  • 1
    in my 4.7.2 install the attribute doesn't work in the class file, I have to add it to the restExtensions config file to make it work
    – dc2009
    Commented Aug 2, 2012 at 9:50
  • The RestExtension attributes have been around since Umbraco 4.6. I use them on 4.7.2 just fine. They even work in the app_code folder. Maybe you're missing a dependency on the server? Commented Aug 2, 2012 at 14:18
  • This is a really clean and nice example - and worked perfectly for me using 4.7.2. Thanks a ton for sharing your great solution.
    – m1m1k
    Commented May 19, 2013 at 23:57
  • You can also just return the json instead of doing any response.write (though the content-type is likely wrong: I'm getting "text/html"). Commented Jul 2, 2013 at 21:21
3

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);
0

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

            })..
8
  • Still returning the value tags. Any other suggestions? What is the difference using reponse.d?
    – Rob Fyffe
    Commented Mar 25, 2012 at 17:49
  • 1
    when a JSON is returned it looks like {"d": "success"} ( Fiddler will help you to see the exact response of the request) Commented Mar 25, 2012 at 17:51
  • Ok I can see with fiddler that the response header looks like, Content-Type: text/xml; charset=utf-8, therefore its still returning XML.
    – Rob Fyffe
    Commented Mar 25, 2012 at 18:16
  • can you post here the response? Commented Mar 25, 2012 at 18:18
  • I have made those edits all ready to the jQuery. The full response: HTTP/1.1 200 OK Content-Type: text/xml; charset=utf-8 Vary: Accept-Encoding Server: Microsoft-IIS/7.5 X-Powered-By: ASP.NET Date: Sun, 25 Mar 2012 18:18:00 GMT Content-Length: 25
    – Rob Fyffe
    Commented Mar 25, 2012 at 18:34
-2

Finally figured it out!

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

3
  • As above, can you provide info? I'm curious. Commented Feb 22, 2013 at 16:22
  • In general, when you find a solution to a particular problem, it is nice to provide a full answer as well. The whole concept is to share information, not only try to get it from others.
    – Kris
    Commented Jul 4, 2014 at 22:13
  • 1
    If anyone needs this, the returnXml = False goes in the constructor for the RestExtensionMethod attribute. See Douglas Ludlow's answer above for an example. Commented Aug 11, 2014 at 19:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.