4

Im asp.net mvc3 c# code returns json list like this:

return Json(new { name = UserNames, imageUrl = ImageUrls });

UserNames and ImageUrls are both List<string> types

And this is my javascript

function StartSearch(text) {
    $.ajax({
        url: '/Shared/Search',
        type: 'POST',
        data: { SearchText: text },
        dataType: 'json',
        success: function (result) {
            $.each(result, function (i, item) {
                alert(result[i].name);
            });
        }
    });
}

How I can get names and ImageUrls?

Thanks

2 Answers 2

5

Access name as a property of result like this result.name[i]

Essentially, result will contain name and imageUrl which are both arrays, just like you have defined in your anonymous type, so your code should be modified like this to display an alert for each name in the name array

function StartSearch(text) {
    $.ajax({
        url: '/Shared/Search',
        type: 'POST',
        data: { SearchText: text },
        dataType: 'json',
        success: function (result) {
            $.each(result.name, function (i, item) {
                alert(item);
           });
        }
    });
}

as $each iterates over the items in the name array, it will pass the item to the second parameter of your call back, i.e. item.

so

$.each(result.name, function (i, item) {
    alert(item);
});

will popup each name.

Notes:

You may want to change the properties on your anonymous type to reflect that they are a collection:

return Json(new { UserNames = UserNames, ImageUrls = ImageUrls });

this way it will make more sense when you iterate over them in your success function.

As AlfalfaStrange pointed out, I didn't demonstrate how you might access both arrays. Which made me think, what is the relationship between user names and image urls?

Is this a list of images for a user? Maybe what you should consider is creating a specific model for this. For instance, UserDisplayModel:

public class UserDisplayModel
{
    public string UserName {get;set;}
    public string ImageUrl {get;set;}
}

In your controller return a list of UserDisplayModels. If this is the case, you'll have to rethink why they are two separate lists in the first place. Maybe ImageUrl should be a field on the User table.

So now, when you're returning a single list, e.g.

List<UserDisplayModel> users = //get users from db
return Json(new { Users = Users});

you can iterate them in one go in js code:

       $.each(result.Users, function (i, item) {
            alert(item.Name);
            alert(item.ImageUrl);
        });
Sign up to request clarification or add additional context in comments.

1 Comment

kudos for the anticipation of a refinement the OP. well played.
4

This alerts the value of Name from each record of each list.

$.each(result, function (i, item) {
    for (var x = 0; x < result.FirstList.length; x++) {
        alert(result.FirstList[x].Name);
        alert(result.SecondList[x].Name);
    }
});

This assumes your Json response if formed correctly. Like this:

return Json(new { FirstList = results, SecondList = otherResults }, JsonRequestBehavior.AllowGet);

But as a side note, I see other problems with your code that you need to address

  1. You're actually not performing a POST, you're searching based on input. Change POST to GET in your Ajax call
  2. Change your action return line to allow for the get and make sure your are returning a JsonResult.
  3. Naming conventions for C# method parameters call for Pascal-casing. Use a lowercase letter for first character

    public JsonResult Search(string searchText) {
        ....
        return Json(new { name = UserNames, imageUrl = ImageUrls }, JsonRequestBehavior.AllowGet);
    }
    

5 Comments

Do you really need to do that inside $.each? couldnt the "for" statement be directly inside the success? Agree with changing POST to GET.
In the .each method, i is each list object so calling .each on result only iterates over the result, so the first object is the first list, the next object is the next list. So to iterate over the items in each list, a second loop is required. For example, in my test, .each(result, function(i, item( { alert[i]; } gives the name of each list, in my case FirstList and SecondList.
in your case, you're not doing anything with i or item, so you could remove the $each, and just iterate using the "for", my first response passed in result.name - name is an array, so $.each(result.name,... alert(item); should work
Yes yours works in that it iterates over the Name list, but then it bypasses the imageUrl list. So I guess it's just semantics, either you call .each on result.name and then a second call after that to .each on result.imageUrl or you call .each on result and then an innerloop on the items of each list
Well it's Json so technically its a dictionary list, it's a list of results because the OP is returning 2 things, a name list, and a Url list. So like I said, in my test, .each on just result gives the name of each returned object, name and imageUrls. So to iterate over each list you call .each on result.name and then a second call on result.imageUrls. I can update the GitHub project that I'm testing with if you'd like to check it out

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.