Getting Started With ASP.Net Web API 2: Day 6

Introduction

We will learn Scaffolding in Web API 2 in this article. Scaffolding is a Text Template Transformation and Toolkit (T4) based code generation framework for ASP.NET. It is a template-based code generator that has been part of Visual Studio since version 2005.

Before reading this article, kindly see my previosu articles on Web API 2, perhaps these articles will make the concept clearer.

Scaffolding is a technique that means "Quick generation of basic template of our application that can be edited and customized the application easily". ASP.NET MVC provides auto generated Views, Controllers, Database, Table Script  and so on. All those layers are generated based on the Model. The field that we need to show or hide in the view can be controlled by the [ScaffoldColumn] attribute.

Scaffolding only gives the basic layout and with this layout we can customize our application, like Create, Read, Update and Delete (CRUD) operations. We create a Model and View for all functions and Controllers with each action item, so we need to write lots of code. Instead of writing this code scaffolding provides a feature to just select a template and model (created as per entity) and automatically creates a controller with all methods and supports a View.

Scaffolding is a Dynamic Data Element that automatically generates code for the Web API. There are some benefits of Scaffolding.

  • Less coding
  • CRUD Operations enabled along with sorting and paging
  • Data Validation
  • Data filter, automatically create foreign key, Boolean fields and enumeration fields

When we are choosing Web API 2, we got some basic templates, some of them are the following:

  • Web API 2 Controller -Empty
  • Web API 2 Controller with actions, using Entity Framework
  • Web API 2 Controller with read/write actions
  • Web API 2 OData Controller with action, using Entity Framework
  • Web API 2 OData Controller with read/write actions

    Let's start to learn step-by-step, how to create a Scaffolding in Web API 2.

    Prerequisites

    There are the following things we need to use when developing a Web API 2 application.

    • Visual Studio 2013
    • ASP.NET Web API 2
    Getting Started

    In this section we will follow some important steps and these are: 
    • Create ASP.NET Web API
    • Add Web API 2 Controller
    • Add a class inside the model

    There are some basic procedures to follow when creating a Web API along with MVC using Visual Studio 2013, we need to also select the Web API Template.

    Step 1

    Open the Visual Studio 2013 and click New Project.

    Step 2

    Select the ASP.NET Web Application and provide a nice name for the project.

    NewProject

    Step 3

    Select the Web API template and click the OK button, by default it will choose MVC along with the Web API.

    SelectTemplate

    Step 4

    Right-click on the Model folder and add a Student class to the model where we define all the necessary fields. In the following image, I have defined some fields like Id, name, Address and College Name.

    StudentClass

    1. public class Student  
    2. {  
    3.     public int Id { getset; }  
    4.     public string Name { getset; }  
    5.     public string Address { getset; }  
    6.     public string CollegeName { getset; }  
    7.       
    8. }  
    Step 5

    Add a new controller using scaffolding. Right-click on the Controller folder and add the controller and click the Add button after selecting the desired template.

    AddingController


    ModelClassAddScaffolding
    Step 6


    Select the Model class that we created and click on the "+" button and edit the name of the New data context type. Provide a meaningful name for the controller.
    1. public class StudentsController : ApiController    
    2. {    
    3.     private studentContext db = new studentContext();    
    4.   
    5.     // GET: api/Students    
    6.     public IQueryable<Student> GetStudents()    
    7.     {    
    8.         return db.Students;    
    9.     }    
    10.   
    11.     // GET: api/Students/5    
    12.     [ResponseType(typeof(Student))]    
    13.     public async Task<IHttpActionResult> GetStudent(int id)    
    14.     {    
    15.         Student student = await db.Students.FindAsync(id);    
    16.         if (student == null)    
    17.         {    
    18.             return NotFound();    
    19.         }    
    20.   
    21.         return Ok(student);    
    22.     }    
    23.   
    24.     // PUT: api/Students/5    
    25.     [ResponseType(typeof(void))]    
    26.     public async Task<IHttpActionResult> PutStudent(int id, Student student)    
    27.     {    
    28.         if (!ModelState.IsValid)    
    29.         {    
    30.             return BadRequest(ModelState);    
    31.         }    
    32.   
    33.         if (id != student.Id)    
    34.         {    
    35.             return BadRequest();    
    36.         }    
    37.   
    38.         db.Entry(student).State = EntityState.Modified;    
    39.   
    40.         try    
    41.         {    
    42.             await db.SaveChangesAsync();    
    43.         }    
    44.         catch (DbUpdateConcurrencyException)    
    45.         {    
    46.             if (!StudentExists(id))    
    47.             {    
    48.                 return NotFound();    
    49.             }    
    50.             else    
    51.             {    
    52.                 throw;    
    53.             }    
    54.         }    
    55.   
    56.         return StatusCode(HttpStatusCode.NoContent);    
    57.     }    
    58.   
    59.     // POST: api/Students    
    60.     [ResponseType(typeof(Student))]    
    61.     public async Task<IHttpActionResult> PostStudent(Student student)    
    62.     {    
    63.         if (!ModelState.IsValid)    
    64.         {    
    65.             return BadRequest(ModelState);    
    66.         }    
    67.   
    68.         db.Students.Add(student);    
    69.         await db.SaveChangesAsync();    
    70.   
    71.         return CreatedAtRoute("DefaultApi"new { id = student.Id }, student);    
    72.     }    
    73.   
    74.     // DELETE: api/Students/5    
    75.     [ResponseType(typeof(Student))]    
    76.     public async Task<IHttpActionResult> DeleteStudent(int id)    
    77.     {    
    78.         Student student = await db.Students.FindAsync(id);    
    79.         if (student == null)    
    80.         {    
    81.             return NotFound();    
    82.         }    
    83.   
    84.         db.Students.Remove(student);    
    85.         await db.SaveChangesAsync();    
    86.   
    87.         return Ok(student);    
    88.     }    
    89.   
    90.     protected override void Dispose(bool disposing)    
    91.     {    
    92.         if (disposing)    
    93.         {    
    94.             db.Dispose();    
    95.         }    
    96.         base.Dispose(disposing);    
    97.     }    
    98.   
    99.     private bool StudentExists(int id)    
    100.     {    
    101.         return db.Students.Count(e => e.Id == id) > 0;    
    102.     }    
    103. }  
    This is the simple procedure to create Scaffolding Web API 2. In the code above we can see that all verbs for a service are being created using Scaffolding. In future articles we will learn further.

    Further Reading

    Getting Started with ASP.NET Web API 2 : Day 7


    Similar Articles