Teodoris
Teodoris

Reputation: 291

How to return IEnumerable values with using ajax in MVC3?

How can I return IEnumerable's values with using ajax. Here is my script:

$.ajax({
         type: "get", url: "street", data: { a: value2 },
         success: function (data) {

          alert(data);

                              }

And here is my controller method:

 [HttpGet]   
        public string street(string a)
        {

            EmlakServicesClient client = new EmlakServicesClient();
            client.ClientCredentials.UserName.UserName = "service_test";
            client.ClientCredentials.UserName.Password = "..";
            client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None;
            Street[] list =client.GetStreet(Convert.ToInt32(a));

                   return ("" + list.FirstOrDefault().StreetName);


        }

As you can see at top I get value but with First Value so how can I get these all values from IEnumarable?

Upvotes: 0

Views: 1780

Answers (3)

Tod Birdsall
Tod Birdsall

Reputation: 19074

I tripped over this while doing a Google search on how to return JSON results using ASP.NET Web API 2. In case someone else is looking for the same solution, here is the solution that worked for me:

// GET: api/Users
public HttpResponseMessage Get()
{
    var users = UserManager.Get(); // returns IEnumerable
    return Request.CreateResponse(HttpStatusCode.OK, users);
}

You can learn more about HttpResponseMessage here.

Upvotes: 0

Shyju
Shyju

Reputation: 218852

return the Collection as JSON

public ActionResult GetsomeItems(int someId)
{
  var someCollection=GetListOfItemsFromSomeWhere(someId)
  return Json(someCollection,JsonRequestBehaviour.AllowGet);
}

Upvotes: 0

SLaks
SLaks

Reputation: 887857

You should use JSON:

return Json(list, JsonRequestBehavior.AllowGet);

You will need to change your action method to return ActionResult.

Upvotes: 3

Related Questions