In this blog we will learn in Web API how to return list of custom type (JSON).
Start visual studio and select 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.
In the new ASP.NET Project dialog, select Web API and Click Ok
We got StudentApp (our Application Name) application with all needed files
Add Model
Click Model Folder, add Student and ResponseModel Class with in 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 Date { set; get; }
- }
Actually Student Class we use for Student Property and ResponseModel Class for Return Type. We will pass all student within ResponseModel Class after few minute we will see to use this Class.
Add Controller
Click Controller Folder-->right button click-->add-->Controller and Select Web API 2 Controller, click Add and give you’re 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="[email protected]",
- Address="Dhaka,Bangladesh"
- });
- students.Add(new Student
- {
- ID = 102,
- Name = "Mitila",
- Email = "[email protected]",
- Address = "Dhaka,Bangladesh"
- });
- students.Add(new Student
- {
- ID = 104,
- Name = "Popy",
- Email = "[email protected]",
- Address = "Dhaka,Bangladesh"
- });
- _objResponseModel.Date = students;
- _objResponseModel.Status = true;
- _objResponseModel.Message = "Data Received successfully";
- return _objResponseModel;
- }
- }
- }
And run, give url (/api/student) we can see output