0

I'm currently working in asp.net mvc 4. I've written a function which return a JSON-object.

This is the function (in my controller)

[HttpPost]
        public ActionResult Login(string email, string password)
        {
            ViewData["Message"] = "None";
            JSONLoginModel model = new JSONLoginModel();

            Account account = _accountRepository.CheckLogin2(email, password);

            if (account != null)
            {
                model.Email = email;
                model.Password = password;
                model.ChangePassword = account.ChangePasswordOnLogin;
            }

            return Json(model);
        }

And this is the JSONLoginModel

[Serializable]
    public class JSONLoginModel
    {
        public string Email { get; set; }
        public string Password { get; set; }
        public bool ChangePassword { get; set; }
    }

I've also written the following JQuery code to catch and use it

$.post("Home/Login", { email: email, password: password }, function (data) {
                alert(data);
                $.each(data, function (index, IntraNoviUser) {
                    if (IntraNoviUser !== undefined && IntraNoviUser !== null) {
                        alert('test1');
                        alert(IntraNoviUser.password, IntraNoviUser.email);
                        alert('test2');
                    }
                });
            });

Everything goes fine until I try to use the result that was returned.

What I get back from my controller is an object which can have 3 options:

  1. null
  2. email + password filled in and changePassword is false
  3. same as 2, but changePassword = true

The problem is that my returned JSON object is never recognized. Any hint on this?

9
  • What does alert(data) display? Have you checked that you're returning valid JSON (and could you include what's returned in the question)? Commented Aug 28, 2012 at 9:16
  • alert(data) shows [object Object]; The other alert shows undefined. I'll update my question with my JSONLoginModel Commented Aug 28, 2012 at 9:19
  • 1
    I was more interested in seeing the actual JSON that's returned to the browser. Commented Aug 28, 2012 at 9:26
  • How can I see this? Since I'm letting mvc do it for me (return json in controller), I have no clue on where to find this. When using firebug, I do see the post gives back teh correct information. Commented Aug 28, 2012 at 9:28
  • 1
    In my Firebug I have Headers, Post, Response, HTML, JSON and Cookies options when expanding a POST AJAX request in the console. The Response tab would be the one you want. Commented Aug 28, 2012 at 9:49

4 Answers 4

1

I Think asp.net resturns json data as d. So you better alert(data.d) and check it.

$.post("Home/Login", { email: email, password: password }, function (data) {
                if(data!=null || data != undefined){
                   if(data.password==true){
                  //do something
                   }
                 else if(data.password==false){//do something

                   }
                }

            });
Sign up to request clarification or add additional context in comments.

5 Comments

I still get [object Object] back even after using .d
can you check what response are you geting in firebug or inspect element in chrome
console -> answer returns {"Email":"email","Password":"password","ChangePassword":false} This is all correct information
hmm data is not a jquery object. Since $.each() can only be applicable to jQuery Obect but data is json object. So $.each wont'work. i am updating the answer
I have already written my own answer. Thanks to you and Anthony Grist I was able to figure it out. It seems I needed to use .Password and .Email because they are defined that way in my intranoviloginmodel.
1

try setting the data type to json like below

$.post("Home/Login", { email: email, password: password }, function (data) {
            alert(data);
            $.each(data, function (index, IntraNoviUser) {
                if (IntraNoviUser !== undefined && IntraNoviUser !== null) {
                    alert('test1');
                    alert(IntraNoviUser.password, IntraNoviUser.email);
                    alert('test2');
                }
            });
        },"json");

notice the last parameter. However the above will iterate each property if the returned data is not an array (or a jquery selection or similar). The parameter IntraNoviUser will hold the property value and the index the name of the property. Since the naming seems a bit odd I suspect you do not want to iterate the properties of the returned object.

if you have one object returned and do not want to iterate the properties then do this

$.post("Home/Login", { email: email, password: password }, function (IntraNoviUser) {
                if (IntraNoviUser !== undefined && IntraNoviUser !== null) {
                    alert('test1');
                    alert(IntraNoviUser.password, IntraNoviUser.email);
                    alert('test2');
                }
            });
        },"json");

aside: capital letters in JavaScript is by convention reserved for Initializer functions (functions that requires to be prefixed with new to work correctly)

EDIT since JavaScript is case sensitive you need to use the same casing in the JS file as in the C# file. That is Email not email, Password not password and so forth. It's a little unfortunate that you will have to break the naming convention of either of the two environments. Personally I prefer to break the C# naming convention since, in a case like this you can make do with an anonymous type

var model =
        {
            email,
            password,
            changePassword = account != null
                                      ? account.ChangePasswordOnLogin 
                                      : false;
        };

return Json(model);

3 Comments

It's true that I'm only return 1 type. I have tried setting "json", but it didn't help me. There was no change in result.
@ThomasSchellekens which one of the above two did you try with json? (and what is the actual string returned by the server?)
I tried the bottom one. The actualstring returned by the server is {"Email":"email","Password":"password","ChangePassword":false} which is correct.
0

Since you are returning a JSON object, rather than an array, your loop function will execute once for each property on the object. If you want to iterate through the data in the object then the signature should be similar to this:

$.each(data, function (key, value) {

Inside the loop you should check the name of the current property by inspecting key and use the value appropriately.

However, as pointed out by Anthony in the comments there doesn't seem to be any need for a loop at all, since you know the names of the properties of the object you can just access them by name.

1 Comment

Since it's a single object, and all the logic inside the loop seems to relate to properties of that object, the iteration seems completely unnecessary.
0

I managed to fix this by using the following code:

    $.post("Home/Login", { email: email, password: password }, function (IntraNoviUser) {
                    if (IntraNoviUser !== undefined && IntraNoviUser !== null) {
                        alert('test1');
                        alert(IntraNoviUser.Password + " " + IntraNoviUser.Email + " " + IntraNoviUser.ChangePassword);
                        alert('test2');
                        var t = IntraNoviUser;
                        alert(t.Password + " " + t.Email + " " + t.ChangePassword);
                    }

});

the JSON that was returned is using the fields from my IntraNoviLoginModel, so it required capitals to work.

I would like to thank Anthony Grist and Ashirvad Singh for pointing me in the right direction here.

1 Comment

Thanks for reminding me, Forgot all about it with my lunch break blush

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.