Niranjan Godbole
Niranjan Godbole

Reputation: 2175

How to return multiple rows of data in web api?

Hi I am doing web api project. I have one get http verb and i want to return multiple rows of data. I am using angular in front end. I am trying as below.

public IEnumerable<NCT_Process_Settings> Get()
{
    NCT_Process_Settings obj = (from c in entityObject.NCT_Process_Settings select c).AsEnumerable();
    return obj;
}

As i know my query returns collection and my object obj is not capable of handling multiple rows of data. So is there any way i can handle this? Any help would be appreciated.Thank you.

Upvotes: 0

Views: 4675

Answers (3)

Karan Mamtora
Karan Mamtora

Reputation: 27

Try this one

        [Route("api/test")]
        public HttpResponseMessage Get()
        {
            HttpResponseMessage response = null;
            List<table_name> obj = new List<table_name>();
            try
            {
                obj = db.table_name.AsNoTracking().ToList();

                response = Request.CreateResponse(HttpStatusCode.OK, obj);
            }
            catch (Exception ex)
            {
                response = Request.CreateResponse(HttpStatusCode.NotFound);
            }
            return response;
        }

then access this api with http://192.168.0.1/api/test

table_name can be a model

Upvotes: 2

user3559349
user3559349

Reputation:

You declare a variable which is a single object, but your trying to assign a collection of objects to it (the result of your query). Change the code to

IEnumerable<NCT_Process_Settings> obj = (from c in entityObject.NCT_Process_Settings select c).AsEnumerable();
return obj;

or

var obj = (from c in entityObject.NCT_Process_Settings select c).AsEnumerable();
return obj;

Upvotes: 1

Sanyami Vaidya
Sanyami Vaidya

Reputation: 809

You can try this, its working fine

public static List<Student> items = new List<Student>();


        [HttpGet]
        public IEnumerable<Student> GetAllStudents()
        {
            if (items.Count() == 0)
            {
                items.Add(new Student { ID = 1, Name = "Ashish", City = "New Delhi", Course = "B.Tech" });
                items.Add(new Student { ID = 2, Name = "Nimit", City = "Noida", Course = "MCA" });
                items.Add(new Student { ID = 3, Name = "Prawah", City = "Dehradun", Course = "B.Tech" });
                items.Add(new Student { ID = 4, Name = "Sumit", City = "Nainital", Course = "MCA" });
            }

            return items;
        }

Upvotes: -1

Related Questions