65.9K
CodeProject is changing. Read more.
Home

Web API Return List of Custom Type (JSON)

starIconstarIconstarIconstarIconstarIcon

5.00/5 (10 votes)

Oct 3, 2016

CPOL
viewsIcon

61119

In this tip, we will learn how to return list of custom type (JSON) data using ASP.NET Web API.

Let's Start

Start Visual Studio and select a new project from the start page. Or from the File menu, select New and then Project. In the Templates pane, select Installed Templates and expand Visual C# node and select web. In the list of project Templates, select ASP.NET Web Application and click OK. And give your Project name Like StudentApp.

1

In the new ASP.NET Project dialog, select Web API and Click Ok.

2

We got StudentApp (our Application Name) application with Installed all need Files.

3

Add Model: Click Model Folder, add Student and ResponseModel Class within Model Folder Student Class:

 public class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Email { get; set; }
    }

ResponseModel Class

 public class ResponseModel
    {
        public string Message { set; get; }
        public bool Status { set; get; }
        public object Data { set; get; }
    }

Actually Student Class we use for Student Property and ResponseModel Class we use for Return Type. we will pass all students within ResponseModel Class. After a few minutes, we will see how to use this Class.

Add Controller: Click Controller Folder, right button click, add click, click Controller and Select Web API 2 Controller, click Add and give your Controller Name (StudentController).

namespace StudentApp.Controllers
{
    public class StudentController : ApiController
    {
        public ResponseModel Get()
        {
            ResponseModel _objResponseModel = new ResponseModel();
            List<Student> students = new List<Student>();
            students.Add(new Student {
                ID = 101,
                Name="Seam",
                Email="seam@gmail.com",
                Address="Dhaka,Bangladesh"
            });
            students.Add(new Student
            {
                ID = 102,
                Name = "Mitila",
                Email = "mitila@gmail.com",
                Address = "Dhaka,Bangladesh"
            });
            students.Add(new Student
            {
                ID = 104,
                Name = "Popy",
                Email = "popy@yahoo.com",
                Address = "Dhaka,Bangladesh"
            });

            _objResponseModel.Data = students;
            _objResponseModel.Status = true;
            _objResponseModel.Message = "Data Received successfully";

            return _objResponseModel;
        }
    }
}

And run, give url (/api/student), we can see output: outApi