Introduction to the Web API Controller

Overview

As mentioned already, ASP.NET and ASP.NET MVC support various techniques to create, maintain, and connect to databases. Besides the regular Model-View-Controller approach, the Web API provides more neutral techniques.

To use a Microsoft SQL Server database in Web API, you can start by creating a model using any of the Entity Framework options and steps we reviewed in previous lessons.

Practical LearningPractical Learning: Introducing Databases in Views

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the New Project dialog box, click ASP.NET Web Application (.NET Framework) and change the project Name to TrafficTicketsSystem1
  4. Click OK
  5. In the New ASP.NET Web Application dialog box, click the Web API icon
  6. Click OK
  7. When asked whether you want to save, click No
  8. In the Solution Explorer, right-click Content -> Add -> Style Sheet
  9. Type TrafficTicketsSystem as the name of the file
  10. Click Add
  11. Change the document as follows:
    body {
        background-color: #FFF;
    }
    
    .bold           { font-weight:   600;     }
    .blue           { color:         #0d3bcf; }
    .box-holder     { margin:        auto;
                      width:         400px;   }
    .traffic-holder { margin:        auto;
                      width:         450px;   }
    .top-pad        { padding-top:   0.50em;  }
    .small          { width:         50px;    }
    .bottom-border  { border-bottom: 1px solid #0d3bcf; }
    .common-font    { font-family:   Georgia, Garamond, 'Times New Roman', serif; }
  12. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  13. Change the document as follows:
    using System.Web.Optimization;
    
    namespace TrafficTicketsSystem1
    {
        public class BundleConfig
        {
            // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js"));
    
                // Use the development version of Modernizr to develop with and learn from. Then, when you're
                // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                            "~/Scripts/modernizr-*"));
    
                bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                          "~/Scripts/bootstrap.js",
                          "~/Scripts/respond.js"));
    
                bundles.Add(new StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/site.css",
                          "~/Content/TrafficTicketsSystem.css"));
            }
        }
    }
  14. If you are using Microsoft SQL Server for your database
    1. Start Microsoft SQL Server and login/connect to the database
    2. In the Object Explorer, right-click the computer name and click New Query
    3. Type the following code:
      USE master;
      GO
      CREATE DATABASE TrafficTicketsSystem;
      GO
      USE TrafficTicketsSystem;
      GO
    4. To execute, right-click inside the Code Editor and click Execute
    5. Click inside the Code Editor, press Ctrl + A to select everything, and press Delete
  15. If you are using a local database
    1. In the Solution Explorer of Microsoft Visual Studio, right-click App_Data -> Add -> New Item...
    2. In the left frame of the Add New Item dialog box, click Data. In the middle frame, click SQL Server Database. Change the database Name to TrafficTicketsSystem
    3. Click Add
    4. In the Solution Explorer, under App_Data, right-click TrafficTicketsSystem.mdf and click Open
    5. In the Server Explorer, right-click TrafficTicketsSystem.mdf and click New Query
  16. In both cases (the Query window in either Microsoft SQL Server or Microsoft Visual Studio), type the following code:
    CREATE TABLE Cameras
    (
    	CameraId INT IDENTITY(1, 1),
    	CameraNumber nvarchar(20),
    	Make nvarchar(40),
    	Model nvarchar(40),
    	[Location] nvarchar(120),
    	CONSTRAINT PK_Cameras PRIMARY KEY(CameraId)
    );
    GO
    CREATE TABLE Drivers
    (
    	DriverId INT IDENTITY(1, 1),
    	DrvLicNumber nvarchar(20),
    	FirstName nvarchar(25),
    	LastName nvarchar(25),
    	[Address] nvarchar(100),
    	City nvarchar(50),
    	County nvarchar(50),
    	[State] nvarchar(5),
    	ZIPCode nvarchar(50),
    	CONSTRAINT PK_Drivers PRIMARY KEY(DriverId)
    );
    GO
    CREATE TABLE Vehicles
    (
    	VehicleId INT IDENTITY(1, 1),
    	TagNumber nvarchar(20),
    	DrvLicNumber nvarchar(20),
    	Make nvarchar(40),
    	Model nvarchar(40),
    	VehicleYear int,
    	Color nvarchar(32),
    	CONSTRAINT PK_Vehicles PRIMARY KEY (VehicleId)
    )
    GO
    CREATE TABLE ViolationTypes
    (
    	ViolationTypeId INT IDENTITY(1, 1),
    	ViolationName nvarchar(30),
    	[Description] nvarchar(max),
    	CONSTRAINT PK_ViolationsTypes PRIMARY KEY(ViolationTypeId)
    );
    GO
    CREATE TABLE TrafficViolations
    (
    	TrafficViolationId INT IDENTITY(1, 1),
    	CameraNumber nvarchar(20),
    	TagNumber nvarchar(20),
    	ViolationName nvarchar(30),
    	ViolationDate date,
    	ViolationTime time(7),
    	PhotoAvailable nvarchar(10),
    	VideoAvailable nvarchar(10),
    	PaymentDueDate date,
    	PaymentDate date,
    	PaymentAmount decimal(8, 2),
    	CONSTRAINT PK_TrafficViolations PRIMARY KEY(TrafficViolationId)
    );
    GO
  17. To execute the code and create the tables, right-click inside the Query window and click Execute
  18. Close the Query window
  19. When asked whether you want to save, click No
  20. In the Solution Explorer, right-click Models -> Add -> ADO.NET Entity Data Model
  21. Change the name to TicketsManagementModel
  22. Click Add
  23. In the Entity Data Model Wizard, click the Code First From Database icon

    Entity Data Model Wizard

    Click Next
  24. In the second page of the Entity Data Model Wizard
    • If you created your database in Microsoft SQL Server, click the New Connection button. In the Connection Properties dialog box, click the Change button, click Microsoft SQL Server, and click OK. In the Server Name text, type the name of the server or type (local). In the Select Or Enter A Database Name combo box, select TrafficTicketsSystem. Click OK.
    • If you created a local database in Microsoft Visual Studio, make sure the top text box displays TrafficTicketsSystem.mdf
  25. Click Next
  26. In the third page of the Entity Data Model Wizard, click the check box of Tables

    Entity Data Model Wizard

  27. Click Finish
  28. In the Solution Explorer, expand Views and expand Shared
  29. Double-click _Layout.cshtml
  30. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width" />
        <title>Traffic Ticket System :: @ViewBag.Title</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    @Html.ActionLink("Traffic Ticket System", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Traffic Tickets", "Index", "Violations", new { area = "" }, null)</li>
                        <li>@Html.ActionLink("Cameras", "Index", "Cameras", new { area = "" }, null)</li>
                        <li>@Html.ActionLink("Violations Types", "Index", "ViolationsTypes", new { area = "" }, null)</li>
                        <li>@Html.ActionLink("Drivers/Owners", "Index", "Drivers", new { area = "" }, null)</li>
                        <li>@Html.ActionLink("Vehicles", "Index", "Vehicles", new { area = "" }, null)</li>
                        <li>@Html.ActionLink("API", "Index", "Help", new { area = "" }, null)</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="container body-content">
            @RenderBody()
            <hr />
            <footer>
                <p class="text-center bold common-font blue">&copy; @DateTime.Now.Year - Traffic Ticket System</p>
            </footer>
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  31. To execute the application, on the main menu, click Debug and click Start Without Debugging:

    Introduction to the Web API Controller

  32. Close the browser and return to your programming environment

A Web API Controller

To use a database in your Web API project, create a class derived from ApiController, a class to which we were introduced already. To get the class, create a scaffold controller using the Entity Framework. Follow the steps exactly as we saw for the Controller class.

Practical LearningPractical Learning: Introducing the Web API Controller

  1. In the Solution Explorer, right-click TrafficTicketsSystem1 -> Add -> New Folder
  2. Type TrafficControllers
  3. In the Solution Explorer, right-click TrafficControllers -> Add -> Controller...
  4. In the middle frame of the dialog box, click Web API 2 Controller With Actions, Using Entity Framework

    Add Scaffold

  5. Click Add
  6. Click the arrow of the Model Class combo box and select Camera (TrafficTicketsSystem1.Models)
  7. Click the arrow of the Data Context Class and select TicketsModel (TrafficTicketsSystem1.Models)

    Add Controller

  8. Click Add
  9. In the Solution Explorer, right-click TrafficControllers -> Add -> New Scaffolded Item...
  10. In the left list of the dialog box, under Common, click Web API
  11. In the middle frame, click Web API 2 Controller With Actions, Using Entity Framework

    Add Scaffold

  12. Click Add
  13. Click the arrow of the Model Class combo box and select Driver (TrafficTicketsSystem1.Models)
  14. In the Data Context Class combo box, make sure TicketsModel (TrafficTicketsSystem1.Models) is selected.
    Click Add
  15. In the Solution Explorer, right-click TrafficControllers -> Add -> Controller...
  16. In the middle frame of the Add Scaffold dialog box, make sure Web API 2 Controller With Actions, Using Entity Framework is selected.
    Click Add
  17. Click the arrow of the Data Context Class and select Vehicle (TrafficTicketsSystem1.Models)
  18. In the Data Context Class combo box, make sure TicketsModel (TrafficTicketsSystem1.Models) is selected.
    Click Add
  19. In the Solution Explorer, right-click TrafficControllers -> Add -> New Scaffolded Item...
  20. In the middle frame of the Add Scaffold dialog box, make sure Web API 2 Controller With Actions, Using Entity Framework is selected.
    Click Add
  21. Click the arrow of the Data Context Class and select TrafficViolation (TrafficTicketsSystem1.Models)
  22. In the Data Context Class combo box, make sure TicketsModel (TrafficTicketsSystem1.Models) is selected.
    Click Add
  23. In the Solution Explorer, right-click TrafficControllers -> Add -> Controller...
  24. In the middle frame of the Add Scaffold dialog box, make sure Web API 2 Controller With Actions, Using Entity Framework is selected.
    Click Add
  25. In the Model Class combo box, select ViolationType (TrafficTicketsSystem1.Models)
  26. In the Data Context Class combo box, make sure TicketsModel (TrafficTicketsSystem1.Models) is selected.
    Click Add

Introduction to jQuery in Web API

The four major operations performed on a database consist of creating, viewing, editing, and removing records. The operations are grouped under the accronym CRUD: Create (a record or insert a record), Read (view a record), Update (or edit/change or replace one or more records), and Delete (or remove one or more records). If you create a controller class using the MVC 5 Controller With Views, Using Entity Framework, Microsoft Visual Studio creates the views necessary to handle CRUD operations.

If you create a controller using the Web API 2 Controller With Actions, Using Entity Framework in the Add Scaffold dialog box, the generated ApiController class only makes available the methods to perform CRUD operations. Microsoft Visual Studio doesn't generate any views associated with the methods. This is not an anomaly. It is by design. You must create the desired webpages yourself, the way you want. If you want to create regular webpages, you can first create a folder of your choice in your project, and then create each of the desired webpages in it. As an alternative, you can create a Controller-based class. In that class, add an action method for each of the operations you will need. Then associate a view to each action method.

To perform the necessary CRUD operations of a database, you can use a Web-based library such as JQuery.

Practical LearningPractical Learning: Introducing jQuery and Databases

  1. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  2. In the middle frame of the Add Scaffold dialog box, click MVC 5 Controller With Read/Write Actions
  3. Click Add
  4. Type Cameras to get CamerasController
  5. Click Add
  6. Change the class as follows:
    using System.Web.Mvc;
    
    namespace TrafficTicketsSystem1.Controllers
    {
        public class CamerasController : Controller
        {
            // GET: Cameras
            public ActionResult Index()
            {
                return View();
            }
    
            // GET: Cameras/Details/5
            public ActionResult Details(int? id)
            {
                return View();
            }
    
            // GET: Cameras/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: Cameras/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Cameras/Edit/5
            public ActionResult Edit(int ? id)
            {
                return View();
            }
    
            // POST: Cameras/Edit/5
            [HttpPost]
            public ActionResult Edit(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Cameras/Delete/5
            public ActionResult Delete(int ?id)
            {
                return View();
            }
    
            // POST: Cameras/Delete/5
            [HttpPost]
            public ActionResult Delete(int id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }

Making an AJAX Call

In previous lessons, we saw that, to communicate with the webserver in jQuery, you can call the $.ajax() method. You can pass a connection as argument. The object you pass as argument to the $.ajax() method must carry the values or object that will be used. You can first create an object and then pass it to the method. Here is an example:

<script type="text/javascript">
    $(document).ready(function () {
        var connection = {};
        
        $.ajax(connection);
    });
</script>

If you are not planning to use the object more than once, you can create it directly in the parentheses of the service. Here is an example:

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({ });
    });
</script>

Records Operations

Creating a Record

If you create a controller using the Web API 2 Controller With Actions, Using Entity Framework, Microsoft Visual Studio declares an entity variable in each class. Along with other methods, Microsoft Visual Studio creates an action whose name starts with Post. Here is an example:

using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Http.Description;
using (TrafficTicketsSystem1.Models);

namespace TrafficTicketsSystem1.Controllers
{
    public class ViolationsController : ApiController
    {
        private TicketsModel db = new TicketsModel();

        . . .

        // POST: api/Violations
        [ResponseType(typeof(Violation))]
        public IHttpActionResult PostViolation(Violation violation)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Violations.Add(violation);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = violation.ViolationID }, violation);
        }

        . . .
    }
}

That method contains the code necessary to add a record to the associated table.

One of the properties of the object, the form method, must have a value as POST. Another property of the object, the url, must specify the path to the entity collection of records. You must also specify the actual values that must be saved. Because we are dealing with an object used in a collection of records (a collection of objects), you can (should/must) provide an object that holds the values. You can first create an object from a var variable, then provide that object as the value of a property named data.

Practical LearningPractical Learning: Creating a Record

  1. In the CamerasController class, right-click inside one of the Create() methods and click Add View...
  2. In the Add View dialog box, make sure the View Name text box is displaying Create. Click Add
  3. Change the document as follows:
    @{
        ViewBag.Title = "New Traffic Camera";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">New Traffic Camera</h2>
    
    <form name="TrafficCamera" method="post">
        <div class="box-holder">
            <div class="form-group row">
                <label for="cameraNumber" class="col-md-3 top-pad">Camera #:</label>
                <div class="col-md-9"><input type="text" id="cameraNumber" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="make" class="col-md-3 top-pad">Make:</label>
                <div class="col-md-9"><input type="text" id="make" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="model" class="col-md-3 top-pad">Model:</label>
                <div class="col-md-9"><input type="text" id="model" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="location" class="col-md-3 top-pad">Location:</label>
                <div class="col-md-9"><input type="text" id="location" class="form-control" /></div>
            </div>
            <p class="text-center"><input type="button" id="btnCreateRecord" class="btn btn-primary" value="Create Traffic Camera" /></p>
        </div>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Traffic Cameras", "Index") ::
        @Html.ActionLink("Traffic Camera Details", "Details") ::
        @Html.ActionLink("Edit/Update Camera Information", "Edit") ::
        @Html.ActionLink("Remove Traffic Camera", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnCreateRecord").click(function () {
                var camera = {
                    CameraNumber: $("#cameraNumber").val(),
                    Make: $("#make").val(),
                    Model: $("#model").val(),
                    Location: $("#location").val()
                };
    
                $.ajax({
                    url: "/api/Cameras",
                    method: "POST",
                    data: camera,
                    success: function (data) {
                        alert("The record has been created and saved.");
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>
  4. In the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...
  5. In the left frame of the Add Scaffold dialog box, under Common, click MVC
  6. In the middle frame, click MVC 5 Controller With Read/Write Actions
  7. Click Add
  8. Type ViolationsTypes to get ViolationsTypesController
  9. Click Add
  10. Change the class as follows:
    using System.Web.Mvc;
    
    namespace TrafficTicketsSystem1.Controllers
    {
        public class ViolationsTypesController : Controller
        {
            . . . No Change
    
            // GET: ViolationsTypes/Details/5
            public ActionResult Details(int? id)
            {
                return View();
            }
    
            . . .
    
            // GET: ViolationsTypes/Edit/5
            public ActionResult Edit(int ? id)
            {
                return View();
            }
    
            . . .
    
            // GET: ViolationsTypes/Delete/5
            public ActionResult Delete(int ?id)
            {
                return View();
            }
    
            . . .
        }
    }
  11. In the class, right-click one of the second Create() method and click Add View...
  12. In the Add View dialog box, make sure the View Name text box is displaying Create. Click Add
  13. Create the form as follows:
    @{
        ViewBag.Title = "Traffic Violation Type";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Traffic Violation Type</h2>
    
    <form name="ViolationType" method="post">
        <div class="traffic-holder">
            <div class="form-group row">
                <label for="vName" class="col-md-3 top-pad">Violation Name:</label>
                <div class="col-md-9"><input type="text" id="vName" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="describe" class="col-md-3 top-pad">Description:</label>
                <div class="col-md-9"><textarea id="describe" rows="10" class="form-control"></textarea></div>
            </div>
    
            <p class="text-center"><input type="button" id="btnDefineViolationType" class="btn btn-primary" value="Create Traffic Camera" /></p>
        </div>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations Types", "Index") ::
        @Html.ActionLink("Details on Violation Type", "Details") ::
        @Html.ActionLink("Edit/Update Violation Type", "Edit") ::
        @Html.ActionLink("Remove Violation Type", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnDefineViolationType").click(function () {
                var camera = {
                    ViolationName: $("#vName").val(),
                    Description: $("#describe").val()
                };
    
                $.ajax({
                    url: "/api/ViolationTypes",
                    method: "POST",
                    data: camera,
                    success: function (data) {
                        alert("The violation type has been defined.");
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>
  14. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  15. In the middle frame of the Add Scaffold dialog box, make sure MVC 5 Controller With Read/Write Actions is selected. Click Add
  16. Type Drivers to get DriversController
  17. Click Add
  18. Change the class as follows:
    using System.Web.Mvc;
    
    namespace TrafficTicketsSystem1.Controllers
    {
        public class DriversController : Controller
        {
            . . .
    
            // GET: Drivers/Details/5
            public ActionResult Details(int? id)
            {
                return View();
            }
    
            . . .
    
            // GET: Drivers/Edit/5
            public ActionResult Edit(int ? id)
            {
                return View();
            }
    
            . . .
    
            // GET: Drivers/Delete/5
            public ActionResult Delete(int ?id)
            {
                return View();
            }
    
            . . .
        }
    }
  19. Right-click one of the Create() methods and click Add View...
  20. Make sure the View Name text box is displaying Create. Click Add
  21. Create a form as follows:
    @{
        ViewBag.Title = "New Vehicle Owner/Driver";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">New Vehicle Owner/Driver</h2>
    
    <form name="VehicleOwnerDriver" method="post">
        <div class="box-holder">
            <div class="form-group row">
                <label for="drvLicNbr" class="col-md-3 top-pad">Drv. Lic. #:</label>
                <div class="col-md-9"><input type="text" id="drvLicNbr" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="fName" class="col-md-3 top-pad">First Name:</label>
                <div class="col-md-9"><input type="text" id="fName" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="lName" class="col-md-3 top-pad">Last Name:</label>
                <div class="col-md-9"><input type="text" id="lName" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="adrs" class="col-md-3 top-pad">Address:</label>
                <div class="col-md-9"><input type="text" id="adrs" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="city" class="col-md-3 top-pad">City:</label>
                <div class="col-md-9"><input type="text" id="city" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="county" class="col-md-3 top-pad">County:</label>
                <div class="col-md-9"><input type="text" id="county" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="state" class="col-md-3 top-pad">State:</label>
                <div class="col-md-9"><input type="text" id="state" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="zip" class="col-md-3 top-pad">ZIPCode:</label>
                <div class="col-md-9"><input type="text" id="zip" class="form-control" /></div>
            </div>
            <p class="text-center"><input type="button" id="btnIssueDriversLicense" class="btn btn-primary" value="Issue a Driver's License" /></p>
        </div>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Drivers/Owners", "Index") ::
        @Html.ActionLink("Driver/Owner Details", "Read") ::
        @Html.ActionLink("Edit/Update Driver/Owner Information", "Update") ::
        @Html.ActionLink("Delete Drivers/Owner Record", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnIssueDriversLicense").click(function () {
                var driver = {
                    DrvLicNumber: $("#drvLicNbr").val(),
                    FirstName:    $("#fName").val(),
                    LastName:     $("#lName").val(),
                    Address:      $("#adrs").val(),
                    City:         $("#city").val(),
                    County:       $("#county").val(),
                    State:        $("#state").val(),
                    ZIPCode:      $("#zip").val()
                };
    
                $.ajax({
                    method: "POST",
                    data:   driver,
                    url:    "/api/Drivers",
                    success: function (data) {
                        alert("The driver's license has been issued.");
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>

Viewing Records

One of the CRUP operations of a database consists of using or opening a document that can display all records. If you create a controller using the Web API 2 Controller With Actions, Using Entity Framework, Microsoft Visual Studio creates a method whose name starts with Get. That method produces all of the records of the table associated with the controller class. Here is an example of the method:

. . .

namespace TrafficTicketsSystem12.TrafficControllers
{
    public class CamerasController : ApiController
    {
        private TicketsModel db = new TicketsModel();

        // GET: api/Cameras
        public IQueryable<Camera> GetCameras()
        {
            return db.Cameras;
        }

        . . .

    }
}

By setting the address of this method as the value of the url property of an $.ajax() method, you can get all the records of a table. Also, you should set the value of the method property as GET.

Practical LearningPractical Learning: Reading Records

  1. In the Solution Explorer, under Controllers, double-click CamerasController.cs to access the controller
  2. In the class, right-click Index() and click Add View...
  3. Make sure the View Name text box is displaying Index. Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Traffic Cameras";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Traffic Cameras</h2>
    
    <table class="table table-striped common-font">
        <tr>
            <th class="bold text-center">Camera Id</th>
            <th class="bold">Camera #</th>
            <th class="bold">Make</th>
            <th class="bold">Model</th>
            <th class="bold">Location</th>
        </tr>
    </table>
    
    <p class="text-center">
        @Html.ActionLink("New Traffic Camera", "Create") ::
        @Html.ActionLink("Traffic Camera Details", "Details") ::
        @Html.ActionLink("Edit/Update Camera Information", "Edit") ::
        @Html.ActionLink("Remove Traffic Camera", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                url: "/api/Cameras",
                method: "GET",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (index, camera) {
                        $("table").append("<tr>"            +
                            "<td class='text-center'>" + camera["CameraId"]     + "</td>" +
                            "<td>" + camera["CameraNumber"] + "</td>" +
                            "<td>" + camera["Make"]         + "</td>" +
                            "<td>" + camera["Model"]        + "</td>" +
                            "<td>" + camera["Location"]     + "</td></tr>");
                    });
                }
            });
        });
    </script>
  5. In the Solution Explorer, under Controllers, double-click DriversController.cs to access the class
  6. Right-click the Index() method and click Add View...
  7. Make sure the View Name text box displays Index
    Click Add
  8. Change the document as follows:
    @{
        ViewBag.Title = "Vehicles Owners/Drivers";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Vehicles Owners/Drivers</h2>
    
    <table class="table table-striped common-font">
        <tr>
            <th class="bold text-center">Driver Id</th>
            <th class="bold">Drv. Lic. #</th>
            <th class="bold">First Name</th>
            <th class="bold">Last Name</th>
            <th class="bold">Address</th>
            <th class="bold">City</th>
            <th class="bold">County</th>
            <th class="bold">State</th>
            <th class="bold">ZIP-Code</th>
        </tr>
    </table>
    
    <p class="text-center">
        @Html.ActionLink("New Driver/Owner", "Create") ::
        @Html.ActionLink("Driver/Owner Details", "Read") ::
        @Html.ActionLink("Edit/Update Driver/Owner Information", "Update") ::
        @Html.ActionLink("Revoke Driver's License", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                method:   "GET",
                dataType: "json",
                url:      "/api/Drivers",
                success: function (data) {
                    $.each(data, function (index, person) {
                        $("table").append("<tr>" +
                            "<td class='text-center'>" + person["DriverId"]     + "</td>" +
                            "<td>" + person["DrvLicNumber"] + "</td>" +
                            "<td>" + person["FirstName"]    + "</td>" +
                            "<td>" + person["LastName"]     + "</td>" +
                            "<td>" + person["Address"]      + "</td>" +
                            "<td>" + person["City"]         + "</td>" +
                            "<td>" + person["County"]       + "</td>" +
                            "<td>" + person["State"]        + "</td>" +
                            "<td>" + person["ZIPCode"]      + "</td></tr>");
                    });
                }
            });
        });
    </script>
  9. In the Solution Explorer, under Views, right-click ViolationsTypes -> Add -> View...
  10. Type Index as the View Name
  11. Click Add
  12. Change the document as follows:
    @{
        ViewBag.Title = "Traffic Violations Types";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Traffic Violations Types</h2>
    
    <table class="table table-striped common-font">
        <tr>
            <th class="bold text-center">Violation Type Id</th>
            <th class="bold">Violation Name</th>
            <th class="bold">Description</th>
        </tr>
    </table>
    
    <p class="text-center">
        @Html.ActionLink("New Violation Type", "Create") ::
        @Html.ActionLink("Details on Violation Type", "Details") ::
        @Html.ActionLink("Edit/Update Violation Type", "Edit") ::
        @Html.ActionLink("Exclude Violation Type", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                url: "/api/ViolationTypes",
                method: "GET",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (index, category) {
                        $("table").append("<tr>"               +
                            "<td class='text-center'>" + category["ViolationTypeId"] + "</td>" +
                            "<td>" + category["ViolationName"]   + "</td>" +
                            "<td>" + category["Description"]     + "</td></tr>");
                    });
                }
            });
        });
    </script>
  13. In the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...
  14. In the middle frame of the Add Scaffold dialog box, make sure MVC 5 Controller With Read/Write Actions is selected. Click Add
  15. Type Vehicles to get VehiclesController
  16. Click Add
  17. Change the document as follows:
    using System.Web.Mvc;
    
    namespace TrafficTicketsSystem1.Controllers
    {
        public class VehiclesController : Controller
        {
            . . .
    
            // GET: Vehicles/Details/5
            public ActionResult Details(int? id)
            {
                return View();
            }
    
            . . .
    
            // GET: Vehicles/Edit/5
            public ActionResult Edit(int ? id)
            {
                return View();
            }
    
            . . .
    
            // GET: Vehicles/Delete/5
            public ActionResult Delete(int ?id)
            {
                return View();
            }
    
            . . .
        }
    }
  18. In the class, right-click the Index() line and click Add View...
  19. Make sure the View Name text box is displaying Index. Click Add
  20. Change the document as follows:
    @{
        ViewBag.Title = "Vehicles Registrations";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Vehicles Registrations</h2>
    
    <table class="table table-striped common-font">
        <tr>
            <th class="bold text-center">Vehicle Id</th>
            <th class="bold">Tag #</th>
            <th class="bold">Drv. Lic. #</th>
            <th class="bold">Make</th>
            <th class="bold">Model</th>
            <th class="bold">Year</th>
            <th class="bold">Color</th>
        </tr>
    </table>
    
    <p class="text-center">
        @Html.ActionLink("New Vehicle Registration", "Create") ::
        @Html.ActionLink("Vehicle Registration Details", "Edit") ::
        @Html.ActionLink("Edit/Update Vehicle Registration Details", "Edit") ::
        @Html.ActionLink("Delete Vehicle Registration", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                method:   "GET",
                dataType: "json",
                url:      "/api/Vehicles",
                success: function (data) {
                    $.each(data, function (index, car) {
                        $("table").append("<tr>"         +
                            "<td class='text-center'>" + car["VehicleId"]    + "</td>" +
                            "<td>" + car["TagNumber"]    + "</td>" +
                            "<td>" + car["DrvLicNumber"] + "</td>" +
                            "<td>" + car["Make"]         + "</td>" +
                            "<td>" + car["Model"]        + "</td>" +
                            "<td>" + car["VehicleYear"]  + "</td>" +
                            "<td>" + car["Color"]        + "</td></tr>");
                    });
                }
            });
        });
    </script>
  21. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  22. In the middle frame of the Add Scaffold dialog box, make sure MVC 5 Controller With Read/Write Actions. Click Add
  23. Type TrafficViolations to get TrafficViolationsController
  24. Click Add
  25. Change the class as follows:
  26. using System.Web.Mvc;
    
    namespace TrafficTicketsSystem1.Controllers
    {
        public class ViolationsController : Controller
        {
            . . .
    
            // GET: Violations/Details/5
            public ActionResult Details(int? id)
            {
                return View();
            }
    
            . . .
    
            // GET: Violations/Edit/5
            public ActionResult Edit(int ? id)
            {
                return View();
            }
    
            . . .
    
            // GET: Violations/Delete/5
            public ActionResult Delete(int ?id)
            {
                return View();
            }
    
            . . .
        }
    }
  27. In the document, right-click Index() and click Add View...
  28. Make sure the View Name text box displays Index. Click Add
  29. Change the document as follows:
    @{
        ViewBag.Title = "Traffic Violations";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Traffic Violations</h2>
    
    <table class="table table-striped common-font">
        <tr>
            <th class="bold text-center">Violation Id</th>
            <th class="bold">Tag #</th>
            <th class="bold">Camera #</th>
            <th class="bold">Violation</th>
            <th class="bold">Date</th>
            <th class="bold">Time</th>
            <th class="bold">Photo Available</th>
            <th class="bold">Video Available</th>
            <th class="bold">Payment Due Date</th>
            <th class="bold">Payment Date</th>
            <th class="bold">Payment Amount</th>
        </tr>
    </table>
    
    <p class="text-center">
        @Html.ActionLink("New Traffic Violation", "Create") ::
        @Html.ActionLink("Traffic Violation Details", "Details") ::
        @Html.ActionLink("Edit/Update Traffic Violation", "Edit") ::
        @Html.ActionLink("Delete/Cancel Traffic Violation", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                method:   "GET",
                dataType: "json",
                url:      "/api/TrafficViolations",
                success: function (data) {
                    $.each(data, function (index, ticket) {
                        $(".table-striped").append("<tr>" +
                            "<td class='text-center'>" + ticket["TrafficViolationId"] + "</td>" +
                            "<td>" + ticket["CameraNumber"] + "</td>" +
                            "<td>" + ticket["TagNumber"] + "</td>" +
                            "<td>" + ticket["ViolationName"] + "</td>" +
                            "<td>" + ticket["ViolationDate"] + "</td>" +
                            "<td>" + ticket["ViolationTime"] + "</td>" +
                            "<td>" + ticket["PhotoAvailable"] + "</td>" +
                            "<td>" + ticket["VideoAvailable"] + "</td>" +
                            "<td>" + ticket["PaymentDueDate"] + "</td>" +
                            "<td>" + ticket["PaymentDate"] + "</td>" +
                            "<td>" + ticket["PaymentAmount"] + "</td></tr>");
                    });
                }
            });
        });
    </script>

Reading or Selecting a Routed Record

To let you locate one particular record, Microsoft Visual Studio creates a method whose name starts with Get and takes one argument. Here is an example of such a method:

. . .

namespace TrafficTicketsSystem1.TrafficControllers
{
    public class CamerasController : ApiController
    {
        private TicketsModel db = new TicketsModel();

        . . .

        // GET: api/Cameras/5
        [ResponseType(typeof(Camera))]
        public IHttpActionResult GetCamera(int id)
        {
            Camera camera = db.Cameras.Find(id);
            if (camera == null)
            {
                return NotFound();
            }

            return Ok(camera);
        }span>

        . . .

    }
}

This method follows the features of routing. It indicates that it needs a value to locate a record. That value should uniquely identify a record. This is the role of the primary key. As a result, you can set the value of url property of the $.ajax() object as we have done so far plus the primary key value as argument.

Practical LearningPractical Learning: Selecting a Record

  1. To create a webpage, in the Solution Explorer, under Views, right-click Cameras -> Add -> View...
  2. Type Details as the name of the view
  3. Press Enter
  4. Change the document as follows:
    @{
        ViewBag.Title = "Traffic Camera Details";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Traffic Camera Details</h2>
    
    <form name="TrafficCamera" method="post">
        <div class="box-holder">
            <div class="form-group row">
                <label for="cameraId" class="col-md-3 top-pad">Camera Id:</label>
                <div class="col-md-3"><input type="text" id="cameraId" class="form-control small" /></div>
                <div class="col-md-3">
                    <input type="button" id="btnFindRecord" class="btn btn-primary" value="Find Camera" />
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Camera #:</label>
                <div class="col-md-9"><span id="cameraNumber"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Make:</label>
                <div class="col-md-9"><span id="make"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Model:</label>
                <div class="col-md-9"><span id="model"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Location:</label>
                <div class="col-md-9"><span id="location"></span></div>
            </div>
        </div>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Traffic Cameras", "Index") ::
        @Html.ActionLink("New Traffic Camera", "Create") ::
        @Html.ActionLink("Edit/Update Camera Information", "Edit") ::
        @Html.ActionLink("Remove Traffic Camera", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnFindRecord").click(function (event) {
                $.ajax({
                    url: "/api/Cameras/" + $("#cameraId").val(),
                    method: "GET",
                    dataType: "json",
                    success: function (data) {
                        $("#cameraId").val(data.CameraId);
                        $("#cameraNumber").text(data.CameraNumber);
                        $("#make").text(data.Make);
                        $("#model").text(data.Model);
                        $("#location").text(data.Location);
                    }
                });
            });
        });
    </script>
  5. In the Solution Explorer, under Views, right-click Drivers -> Add -> View...
  6. Type Details as the name of the view
  7. Press Enter
  8. Change the document as follows:
    @{
        ViewBag.Title = "Driver/Owner Details";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Driver/Owner Details</h2>
    
    <form name="DriverOwner" method="post">
        <div class="box-holder">
            <div class="form-group row">
                <label for="cameraId" class="col-md-3 top-pad">Driver ID:</label>
                <div class="col-md-3"><input type="text" id="driverId" class="form-control small" /></div>
                <div class="col-md-3">
                    <input type="button" id="btnLocateDriver" class="btn btn-primary" value="Locate Driver/Owner" />
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Drv. Lic. #:</label>
                <div class="col-md-9"><span id="drvLicNbr"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">First Name:</label>
                <div class="col-md-9"><span id="fname"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Last Name:</label>
                <div class="col-md-9"><span id="lname" /></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Address:</label>
                <div class="col-md-9"><span id="adrs"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">City:</label>
                <div class="col-md-9"><span id="city"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">County:</label>
                <div class="col-md-9"><span id="county"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">State:</label>
                <div class="col-md-9"><span id="state"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">ZIP-Code:</label>
                <div class="col-md-9"><span id="zip"></span></div>
            </div>
        </div>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Traffic Cameras", "Index") ::
        @Html.ActionLink("New Traffic Camera", "Create") ::
        @Html.ActionLink("Edit/Update Camera Information", "Edit") ::
        @Html.ActionLink("Remove Traffic Camera", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $(".btn-primary").on("click", function (event) {
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url:      "/api/Drivers/" + $("input[id='driverId']").val(),
                    success: function (data) {
                        $("span[id='drvLicNbr']").text(data.DrvLicNumber);
                        $("span[id='fname']").text(data.FirstName);
                        $("span[id='lname']").text(data.LastName);
                        $("span[id='adrs']").text(data.Address);
                        $("span[id='city']").text(data.City);
                        $("span[id='county']").text(data.County);
                        $("span[id='state']").text(data.State);
                        $("span[id='zip']").text(data.ZIPCode);
                    }
                });
            });
        });
    </script>
  9. In the Solution Explorer, under Views, right-click Vehicles -> Add -> View...
  10. Type Details as the name of the view
  11. Press Enter
  12. Change the document as follows:
    @{
        ViewBag.Title = "Vehicle Details";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Vehicle Details</h2>
    
    <form name="DriverOwner" method="post">
        <div class="box-holder">
            <div class="form-group row">
                <label for="cameraId" class="col-md-3 top-pad">Vehicle Id:</label>
                <div class="col-md-3"><input type="text" id="carId" class="form-control small" /></div>
                <div class="col-md-3">
                    <input type="button" id="btnGetVehicle" class="btn btn-primary" value="Get the Vehicle" />
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Tag #:</label>
                <div class="col-md-9"><span class="tagNbr"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Drv. Lic. #:</label>
                <div class="col-md-9"><span class="dln"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Make:</label>
                <div class="col-md-9"><span class="make" /></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Model:</label>
                <div class="col-md-9"><span class="mdl"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Year:</label>
                <div class="col-md-9"><span class="year"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Color:</label>
                <div class="col-md-9"><span class="color"></span></div>
            </div>
        </div>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Traffic Cameras", "Index") ::
        @Html.ActionLink("New Traffic Camera", "Create") ::
        @Html.ActionLink("Edit/Update Camera Information", "Edit") ::
        @Html.ActionLink("Remove Traffic Camera", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $(".btn-primary").on("click", function (event) {
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url: "/api/Vehicles/" + $(".small").val(),
                    success: function (data) {
                        $("span.tagNbr").text(data.TagNumber);
                        $("span.dln").text(data.DrvLicNumber);
                        $("span.make").text(data.Make);
                        $("span.mdl").text(data.Model);
                        $("span.year").text(data.VehicleYear);
                        $("span.color").text(data.Color);
                    }
                });
            });
        });
    </script>
  13. In the Solution Explorer, under Views, right-click ViolationsTypes -> Add -> View...
  14. Type Details as the name of the view
  15. Press Enter
  16. Change the document as follows:
    @{
        ViewBag.Title = "Volation Type Details";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Volation Type Details</h2>
    
    <form name="TrafficCamera" method="post">
        <div class="box-holder">
            <div class="form-group row">
                <label for="cameraId" class="col-md-3 top-pad">Volation Type ID:</label>
                <div class="col-md-3"><input type="text" id="categoryId" class="form-control small" /></div>
                <div class="col-md-3">
                    <input type="button" id="btnFindVolationType" class="btn btn-primary" value="Find Camera" />
                </div>
            </div>
            <div class="form-group row">
                <label for="cameraNumber" class="col-md-3 top-pad">Volation Type:</label>
                <div class="col-md-9"><input type="text" id="vType" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="describe" class="col-md-3 top-pad">Description:</label>
                <div class="col-md-9"><textarea id="describe" class="form-control" rows="5"></textarea></div>
            </div>
        </div>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations Types", "Index") ::
        @Html.ActionLink("New Violation Type", "Create") ::
        @Html.ActionLink("Edit/Update Violation Type", "Edit") ::
        @Html.ActionLink("Exclude Violation Type", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnFindVolationType").click(function (event) {
                $.ajax({
                    url: "/api/ViolationTypes/" + $("#categoryId").val(),
                    method: "GET",
                    dataType: "json",
                    success: function (data) {
                        $("#categoryId").val(data.ViolationTypeId);
                        $("#vType").val(data.ViolationName);
                        $("#describe").val(data.Description);
                    }
                });
            });
        });
    </script>
  17. In the Solution Explorer, under Views, right-click TrafficViolations -> Add -> View...
  18. Type Details as the name of the view
  19. Press Enter
  20. Change the document as follows:
    @{
        ViewBag.Title = "Violation/Infraction Details";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Violation/Infraction Details</h2>
    
    <form name="DriverOwner" method="post">
        <div class="traffic-holder">
            <div class="form-group row">
                <label for="cameraId" class="col-md-3 top-pad">Violation Id:</label>
                <div class="col-md-3"><input type="text" id="infractionId" class="form-control small" /></div>
                <div class="col-md-3">
                    <input type="button" id="btnShowViolation" class="btn btn-primary" value="Show the Violation" />
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Camera:</label>
                <div class="col-md-8"><span name="capturingCamera"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Vehicle Tag #:</label>
                <div class="col-md-8"><span name="violatingVehicle"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Violation Type:</label>
                <div class="col-md-8"><span name="InfrationCategory" /></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Violation Date:</label>
                <div class="col-md-8"><span name="date-of-infraction"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Violation Time:</label>
                <div class="col-md-8"><span name="time-of-infraction"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Photo is Available:</label>
                <div class="col-md-8"><span name="steady-photo-available"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Video is Available:</label>
                <div class="col-md-8"><span name="streaming-video-available"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Payment Due Date:</label>
                <div class="col-md-8"><span name="payment due date"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Payment Date:</label>
                <div class="col-md-8"><span name="last-day-payment"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Amount Owed:</label>
                <div class="col-md-8"><span name="amount-owed"></span></div>
            </div>
        </div>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violation", "Index") ::
        @Html.ActionLink("New Traffic Violation", "Create") ::
        @Html.ActionLink("Edit/Update Traffic Violation", "Edit") ::
        @Html.ActionLink("Delete/Cancel Traffic Violation", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $(".btn-primary").on("click", function (event) {
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url: "/api/TrafficViolations/" + $("#infractionId").val(),
                    success: function (data) {
                        $("span[name$='Camera']").text(data.CameraNumber);
                        $("span[name$='Vehicle']").text(data.TagNumber);
                        $("span[name$='Category']").text(data.ViolationName);
                        $("span[name|='date']").text(data.ViolationDate);
                        $("span[name|='time']").text(data.ViolationTime);
                        $("span[name*='photo']").text(data.PhotoAvailable);
                        $("span[name*='video']").text(data.VideoAvailable);
                        $("span[name~='due']").text(data.PaymentDueDate);
                        $("span[name='last-day-payment']").text(data.PaymentDate);
                        $("span[name='amount-owed']").text(data.PaymentAmount);
                    }
                });
            });
        });
    </script>

Filtering Records

Data Analysis consists of selecting one or more records based on a condition. To do this in the Web API and jQuery, in the body of a $each() function, you can use a conditional statement.

Practical LearningPractical Learning: Filtering a Record

  1. In the Solution Explorer, under Controllers, double-click VehiclesController.cs
  2. In the class, right-click one of the Create() methods and click Add View...
  3. Make sure the View Name text box is displaying Create. Click Add
  4. Create a form as follows:
    @{
        ViewBag.Title = "New Vehicle Registration";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">New Vehicle Registration</h2>
    
    <form name="VehicleRegistration" method="post">
        <div class="traffic-holder">
            <div class="form-group row">
                <label for="tagNbr" class="col-md-3 top-pad">Vehicle Tag #:</label>
                <div class="col-md-9"><input type="text" id="tagNbr" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="drvLicNbr" class="col-md-3 top-pad">Drv. Lic. #:</label>
                <div class="col-md-9"><input type="text" id="drvLicNbr" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="owner" class="col-md-3 top-pad">Owner/Driver:</label>
                <div class="col-md-9"><input type="text" id="owner" name="owner" class="form-control" disabled /></div>
            </div>
            <div class="form-group row">
                <label for="make" class="col-md-3 top-pad">Make:</label>
                <div class="col-md-9"><input type="text" id="make" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="model" class="col-md-3 top-pad">Model:</label>
                <div class="col-md-9"><input type="text" id="model" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="year" class="col-md-3 top-pad">Year:</label>
                <div class="col-md-9"><input type="text" id="year" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="clr" class="col-md-3 top-pad">Color:</label>
                <div class="col-md-9"><input type="text" id="clr" class="form-control" /></div>
            </div>
    
            <p class="text-center"><input type="button" id="btnRegisterVehicle" class="btn btn-primary" value="Register this Vehicle" /></p>
        </div>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Vehicles Registrations", "Index") ::
        @Html.ActionLink("Vehicle Registration Details", "Details") ::
        @Html.ActionLink("Edit/Update Vehicle Registration", "Edit") ::
        @Html.ActionLink("Delete Vehicle Registration", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#drvLicNbr").blur(function (event) {
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url:      "/api/Drivers",
                    success: function (data) {
                        $.each(data, function (index, person) {
                            if (person["DrvLicNumber"] === $("#drvLicNbr").val()) {
                                $("input[id='owner']").val(person["FirstName"] + " " +
                                                           person["LastName"] + " (Drv. Lic. #: " +
                                                           person["DrvLicNumber"] + ")");
                            }
                        });
                    }
                });
            }); // Driver's License Number Lost Focus
    
    
            $("#btnRegisterVehicle").click(function () {
                var car = {
                    TagNumber:    $("#tagNbr").val(),
                    DrvLicNumber: $("#drvLicNbr").val(),
                    Make:         $("#make").val(),
                    Model:        $("#model").val(),
                    VehicleYear:  $("#year").val(),
                    Color:        $("#clr").val()
                };
    
                $.ajax({
                    data:   car,
                    method: "POST",
                    url:    "/api/Vehicles",
                    success: function (data) {
                        alert("The vehicle has been registered.");
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>
  5. In the Solution Explorer, under Views, right-click TrafficViolations -> Add -> View...
  6. Type Create as the name of the view
  7. Press Enter
  8. Change the document as follows:
    @{
        ViewBag.Title = "New Traffic Ticket";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Traffic Violation - New Traffic Ticket</h2>
    
    <form name="VehicleOwnerDriver" method="post">
        <div class="traffic-holder">
            <div class="form-group row">
                <label for="cmrNbr" class="col-md-3 top-pad">Camera #:</label>
                <div class="col-md-9"><input type="text" id="cmrNbr" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3 top-pad">Camera Details:</label>
                <div class="col-md-9"><input type="text" id="cmrDetails" class="form-control camera-details" disabled /></div>
            </div>
            <div class="form-group row">
                <label for="tagNbr" class="col-md-3 top-pad">Vehicle Tag #:</label>
                <div class="col-md-9"><input type="text" id="tagNbr" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3 top-pad">Vehicle Details:</label>
                <div class="col-md-9"><input type="text" name="vehicle" class="form-control" disabled /></div>
            </div>
            <div class="form-group row">
                <label for="category" class="col-md-3 top-pad">Violation Type:</label>
                <div class="col-md-9">
                    <select id="category" class="form-control"></select>
                </div>
            </div>
            <div class="form-group row">
                <label for="county" class="col-md-3 top-pad">Violation Date:</label>
                <div class="col-md-9"><input type="date" id="trafficDate" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="trafficTime" class="col-md-3 top-pad">Violation Time:</label>
                <div class="col-md-9"><input type="time" id="trafficTime" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="photo" class="col-md-3 top-pad">Photo Available:</label>
                <div class="col-md-9">
                    <select id="photo" class="form-control">
                        <option value="No">No</option>
                        <option value="Yes">Yes</option>
                    </select>
                </div>
            </div>
            <div class="form-group row">
                <label for="photo" class="col-md-3 top-pad">Video Available:</label>
                <div class="col-md-9">
                    <select type="checkbox" id="video" class="form-control">
                        <option value="No">No</option>
                        <option value="Yes">Yes</option>
                    </select>
                </div>
            </div>
            <div class="form-group row">
                <label for="pdd" class="col-md-3 top-pad">Payment Due Date:</label>
                <div class="col-md-9"><input type="date" id="pdd" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="pmtDate" class="col-md-3 top-pad">Payment Date:</label>
                <div class="col-md-9"><input type="date" id="pmtDate" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="pmtAmt" class="col-md-3 top-pad">Payment Amount:</label>
                <div class="col-md-9"><input type="text" id="pmtAmt" class="form-control" /></div>
            </div>
            <p class="text-center"><input type="button" id="btnCreateTicket" class="btn btn-primary" value="Create Traffic Violation" /></p>
        </div>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations", "Index") ::
        @Html.ActionLink("Traffic Violation Details", "Details") ::
        @Html.ActionLink("Edit/Update Traffic Violation", "Edit") ::
        @Html.ActionLink("Scrap Traffic Violation", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                url: "/api/ViolationTypes",
                method: "GET",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (index, category) {
                        $("#category").append("<option value = '" + category["ViolationName"] + "'>" +
                                              category["ViolationName"] + "</option>");
                    });
                }
            });
    
            $("#cmrNbr").blur(function (event) {
                $.ajax({
                    method: "GET",
                    dataType: "json",
                    url: "/api/Cameras",
                    success: function (data) {
                        $.each(data, function (index, device) {
                            if (device["CameraNumber"] === $("#cmrNbr").val()) {
                                $(".camera-details").val(device["Make"] + " " +
                                    device["Model"] + " (Location: " +
                                    device["Location"] + ")");
                            }
                        });
                    }
                });
            }); // Camera Number Lost Focus
    
            $("#tagNbr").blur(function (event) {
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url:      "/api/Vehicles",
                    success: function (data) {
                        $.each(data, function (index, car) {
                            if (car["TagNumber"] === $("#tagNbr").val()) {
                                $("input[name='vehicle']").val(car["Make"] + " " +
                                    car["Model"] + " (" +
                                    car["VehicleYear"] + ", " + car["Color"] + ")");
                            }
                        });
                    }
                });
            }); // Vehicle Tag Number Lost Focus
    
            $("#btnCreateTicket").click(function () {
                var ticket = {
                    CameraNumber: $("#cmrNbr").val(),
                    TagNumber: $("#tagNbr").val(),
                    ViolationName: $("#category").val(),
                    ViolationDate: $("#trafficDate").val(),
                    ViolationTime: $("#trafficTime").val(),
                    PhotoAvailable: $("#photo").val(),
                    VideoAvailable: $("#video").val(),
                    PaymentDueDate: $("#pdd").val(),
                    PaymentDate: $("#pmtDate").val(),
                    PaymentAmount: $("#pmtAmt").val()
                };
    
                $.ajax({
                    method: "POST",
                    data: ticket,
                    url: "/api/TrafficViolations",
                    success: function (data) {
                        alert("A ticket for the traffic violation has been issued.");
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>

Updating or Editing a Record

To assist you in changing a record in Web API, Microsoft Visual Studio creates a method whose name starts with Put. The method takes two arguments. Here is an example of such a method:

. . .

namespace TrafficTicketsSystem12.TrafficControllers
{
    public class CamerasController : ApiController
    {
        private TicketsModel db = new TicketsModel();

        . . .

        // PUT: api/Cameras/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PutCamera(int id, Camera camera)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != camera.CameraID)
            {
                return BadRequest();
            }

            db.Entry(camera).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CameraExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        . . .
    }
}

The first argument plays the same role we saw for the method used to view a record: that argument helps to uniquely locate a record. The second argument is an object that holds values of the record you want to change. To proceed in jQuery, first find the record that must be updated, and display that record to the visitor to make the necessary changes. When creating the object passed to the $.ajax() method, the value of the url property must include both the path to the records and a suffix that indicates the record to be changed. The HTML METHOD used to edit or replace a record is named PUT.

ApplicationPractical Learning: Viewing a Record

  1. In the Solution Explorer, under Views, right-click ViolationsTypes -> Add -> View...
  2. Type Edit as the name of the view
  3. Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Edit/Update Violation Type";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Edit/Update Violation Type</h2>
    
    <form name="TrafficCamera" method="post">
        <div class="box-holder">
            <div class="form-group row">
                <label for="cameraId" class="col-md-3 top-pad">Violation Type ID:</label>
                <div class="col-md-3"><input type="text" id="vTypeId" class="form-control small" /></div>
                <div class="col-md-3">
                    <input type="button" id="btnSearchType" class="btn btn-primary" value="Find Violation Type" />
                </div>
            </div>
            <div class="form-group row">
                <label for="category" class="col-md-3 top-pad">Violation Type:</label>
                <div class="col-md-9"><input type="text" id="category" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="describe" class="col-md-3 top-pad">Description:</label>
                <div class="col-md-9"><textarea id="describe" class="form-control"></textarea></div>
            </div>
        </div>
        <p class="text-center"><input type="button" id="btnUpdateViolationType" class="btn btn-primary" value="Update Violation Type" /></p>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations Types", "Index") ::
        @Html.ActionLink("New Violation Type", "Create") ::
        @Html.ActionLink("Details on Violation Type", "Details") ::
        @Html.ActionLink("Remove Violation Type", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnSearchType").click(function (event) {
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url:      "/api/ViolationTypes/" + $("#vTypeId").val(),
                    success: function (data) {
                        $("#category").val(data.ViolationName);
                        $("#describe").val(data.Description);
                    }
                });
            });
    
            $("#btnUpdateViolationType").click(function (event) {
                var infraction = {
                    ViolationTypeID: $("#vTypeId").val(),
                    ViolationName:   $("#category").val(),
                    Description:     $("#describe").val()
                };
                $.ajax({
                    method: "PUT",
                    data:   infraction,
                    url:    "/api/ViolationTypes/" + $("#vTypeId").val(),
                    success: function (data) {
                        alert("The violation type has been updated.")
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>
  5. In the Solution Explorer, under Views, right-click Drivers -> Add -> View...
  6. Type Edit as the name of the view
  7. Click Add
  8. Change the document as follows::
    @{
        ViewBag.Title = "Edit/Update Driver Information";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Edit/Update Driver Information</h2>
    
    <form name="TrafficCamera" method="post">
        <div class="box-holder">
            <div class="form-group row">
                <label for="chauffeur" class="col-md-3 top-pad">Driver ID:</label>
                <div class="col-md-3"><input type="text" id="chauffeur" class="form-control small" /></div>
                <div class="col-md-3">
                    <input type="button" id="btnGetDriver" class="btn btn-primary" value="Find Driver" />
                </div>
            </div>
            <div class="form-group row">
                <label for="drvLicNbr" class="col-md-3 top-pad">Drv. Lic. #:</label>
                <div class="col-md-9"><input type="text" id="drvLicNbr" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="fName" class="col-md-3 top-pad">First Name:</label>
                <div class="col-md-9"><input type="text" id="fName" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="lName" class="col-md-3 top-pad">Last Name:</label>
                <div class="col-md-9"><input type="text" id="lName" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="adrs" class="col-md-3 top-pad">Address:</label>
                <div class="col-md-9"><input type="text" id="adrs" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="city" class="col-md-3 top-pad">City:</label>
                <div class="col-md-9"><input type="text" id="city" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="county" class="col-md-3 top-pad">County:</label>
                <div class="col-md-9"><input type="text" id="county" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="state" class="col-md-3 top-pad">State:</label>
                <div class="col-md-9"><input type="text" id="state" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="zip" class="col-md-3 top-pad">ZIP-Code:</label>
                <div class="col-md-9"><input type="text" id="zip" class="form-control" /></div>
            </div>
        </div>
        <p class="text-center"><input type="button" id="btnUpdateRecord" class="btn btn-primary" value="Update Camera Details" /></p>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Drivers/Owners", "Index") ::
        @Html.ActionLink("New Driver", "Create") ::
        @Html.ActionLink("Driver/Owner Details", "Details") ::
        @Html.ActionLink("Delete Drivers/Owner Record", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnGetDriver").click(function (event) {
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url: "/api/Drivers/" + $("#chauffeur").val(),
                    success: function (data) {
                        $("#tagNbr").val(data.TagNumber);
                        $("#drvLicNbr").val(data.DrvLicNumber);
                        $("#fName").val(data.FirstName);
                        $("#lName").val(data.LastName);
                        $("#adrs").val(data.Address);
                        $("#city").val(data.City);
                        $("#county").val(data.County);
                        $("#state").val(data.State);
                        $("#zip").val(data.ZIPCode);
                    }
                });
            });
    
            $("#btnUpdateRecord").click(function (event) {
                var dvr = {
                    DriverID:     $("#chauffeur").val(),
                    DrvLicNumber: $("#drvLicNbr").val(),
                    FirstName:    $("#fName").val(),
                    LastName:     $("#lName").val(),
                    Address:      $("#adrs").val(),
                    TagNumber:    $("#tagNbr").val(),
                    City:         $("#city").val(),
                    County:       $("#county").val(),
                    State:        $("#state").val(),
                    ZIPCode:      $("#zip").val()
                };
                $.ajax({
                    data: dvr,
                    method: "PUT",
                    url: "/api/Drivers/" + $("#chauffeur").val(),
                    success: function (data) {
                        alert("The driver/owner information is no up-to-date.")
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>
  9. In the Solution Explorer, under Views, right-click Cameras -> Add -> View...
  10. Type Edit as the name of the view
  11. Press Enter
  12. Create a form as follows:
    @{
        ViewBag.Title = "Edit/Update Camera Information";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Edit/Update Camera Information</h2>
    
    <form name="TrafficCamera" method="post">
        <div class="box-holder">
            <div class="form-group row">
                <label for="cameraId" class="col-md-3 top-pad">Camera ID:</label>
                <div class="col-md-3"><input type="text" id="cameraId" class="form-control small" /></div>
                <div class="col-md-3">
                    <input type="button" id="btnFindRecord" class="btn btn-primary" value="Find Camera" />
                </div>
            </div>
            <div class="form-group row">
                <label for="cameraNumber" class="col-md-3 top-pad">Camera #:</label>
                <div class="col-md-9"><input type="text" id="cameraNumber" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="make" class="col-md-3 top-pad">Make:</label>
                <div class="col-md-9"><input type="text" id="make" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="model" class="col-md-3 top-pad">Model:</label>
                <div class="col-md-9"><input type="text" id="model" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="location" class="col-md-3 top-pad">Location:</label>
                <div class="col-md-9"><input type="text" id="location" class="form-control" /></div>
            </div>
        </div>
        <p class="text-center"><input type="button" id="btnUpdateRecord" class="btn btn-primary" value="Update Camera Details" /></p>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Traffic Cameras", "Index") ::
        @Html.ActionLink("New Traffic Camera", "Create") ::
        @Html.ActionLink("Traffic Camera Details", "Details") ::
        @Html.ActionLink("Remove Traffic Camera", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnFindRecord").click(function (event) {
                $.ajax({
                    url: "/api/Cameras/" + $("#cameraId").val(),
                    method: "GET",
                    dataType: "json",
                    success: function (data) {
                        $("#cameraNumber").val(data.CameraNumber);
                        $("#make").val(data.Make);
                        $("#model").val(data.Model);
                        $("#location").val(data.Location);
                    }
                });
            });
    
            $("#btnUpdateRecord").click(function (event) {
                var camera = {
                    CameraID: $("#cameraId").val(),
                    CameraNumber: $("#cameraNumber").val(),
                    Make: $("#make").val(),
                    Model: $("#model").val(),
                    Location: $("#location").val()
                };
                $.ajax({
                    url: "/api/Cameras/" + $("#cameraId").val(),
                    method: "PUT",
                    data: camera,
                    success: function (data) {
                        alert("The traffic camera data has been updated and saved.")
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>
  13. In the Solution Explorer, under Views, right-click Vehicles -> Add -> View...
  14. Type Edit as the name of the view
  15. Click Add
  16. Change the document as follows::
    @{
        ViewBag.Title = "Edit/Update Vehicle Information";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Edit/Update Vehicle Information</h2>
    
    <form name="TrafficCamera" method="post">
        <div class="box-holder">
            <div class="form-group row">
                <label for="carId" class="col-md-3 top-pad">Vehicle Id:</label>
                <div class="col-md-3"><input type="text" id="carId" class="form-control small" /></div>
                <div class="col-md-3">
                    <input type="button" id="btnLocateVehicle" class="btn btn-primary" value="Locate Vehicle/Car" />
                </div>
            </div>
            <div class="form-group row">
                <label for="drvLicNbr" class="col-md-3 top-pad">Drv. Lic. #:</label>
                <div class="col-md-9"><input type="text" id="drvLicNbr" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="owner" class="col-md-3 top-pad">Owner/Driver:</label>
                <div class="col-md-9"><input type="text" id="owner" name="owner" class="form-control" disabled /></div>
            </div>
            <div class="form-group row">
                <label for="tagNbr" class="col-md-3 top-pad">Vehicle Tag #:</label>
                <div class="col-md-9"><input type="text" id="tagNbr" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="make" class="col-md-3 top-pad">Make:</label>
                <div class="col-md-9"><input type="text" id="make" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="model" class="col-md-3 top-pad">Model:</label>
                <div class="col-md-9"><input type="text" id="model" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="year" class="col-md-3 top-pad">Year:</label>
                <div class="col-md-9"><input type="text" id="year" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="color" class="col-md-3 top-pad">Color:</label>
                <div class="col-md-9"><input type="text" id="color" class="form-control" /></div>
            </div>
        </div>
        <p class="text-center"><input type="button" id="btnUpdateRecord" class="btn btn-primary" value="Update Camera Details" /></p>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Vehicles Registrations", "Index") ::
        @Html.ActionLink("Create Vehicle Registration", "Edit") ::
        @Html.ActionLink("Vehicle Registration Details", "Details") ::
        @Html.ActionLink("Delete Vehicle Registration", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnLocateVehicle").click(function (event) {
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url:      "/api/Vehicles/" + $("#carId").val(),
                    success: function (data) {
                        $("#tagNbr").val(data.TagNumber);
                        $("#drvLicNbr").val(data.DrvLicNumber);
                        $("#make").val(data.Make);
                        $("#model").val(data.Model);
                        $("#year").val(data.VehicleYear);
                        $("#color").val(data.Color);
                    }
                });
    
                $.ajax({
                    method: "GET",
                    dataType: "json",
                    url: "/api/Drivers",
                    success: function (data) {
                        $.each(data, function (index, person) {
                            if (person["DrvLicNumber"] === $("#drvLicNbr").val()) {
                                $("input[id='owner']").val(person["FirstName"] + " " +
                                    person["LastName"] + " (Drv. Lic. #: " +
                                    person["DrvLicNumber"] + ")");
                            } // If
                        }); // Each
                    } // Successful AJAX
                }); // $.ajax
            });
    
            $("#btnUpdateRecord").click(function (event) {
                var car = {
                    VehicleId: $("#carId").val(),
                    TagNumber: $("#tagNbr").val(),
                    DrvLicNumber: $("#drvLicNbr").val(),
                    Make: $("#make").val(),
                    Model: $("#model").val(),
                    VehicleYear: $("#year").val(),
                    Color: $("#color").val()
                };
                $.ajax({
                    data: car,
                    method: "PUT",
                    url: "/api/Vehicles/" + $("#carId").val(),
                    success: function (data) {
                        alert("The information about the vehicle has been updated.")
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>
  17. In the Solution Explorer, under Views, right-click TrafficViolations -> Add -> View...
  18. Type Edit as the name of the View
  19. Click Add
  20. Change the document as follows:
    @{
        ViewBag.Title = "Edit/Update Violation Details";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Edit/Update Violation Details</h2>
    
    <form name="TrafficCamera" method="post">
        <div class="traffic-holder">
            <div class="form-group row">
                <label for="infractionId" class="col-md-3 top-pad">Violation Id:</label>
                <div class="col-md-3"><input type="text" id="infractionId" class="form-control small" /></div>
                <div class="col-md-3">
                    <input type="button" id="btnLocateViolation" class="btn btn-primary" value="Locate Violation" />
                </div>
            </div>
            <div class="form-group row">
                <label for="cmrNbr" class="col-md-3 top-pad">Camera #:</label>
                <div class="col-md-9"><input type="text" id="cmrNbr" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3 top-pad">Camera Details:</label>
                <div class="col-md-9"><input type="text" id="cmrDetails" class="form-control camera-details" disabled /></div>
            </div>
            <div class="form-group row">
                <label for="tagNbr" class="col-md-3 top-pad">Vehicle Tag #:</label>
                <div class="col-md-9"><input type="text" id="tagNbr" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3 top-pad">Vehicle Details:</label>
                <div class="col-md-9"><input type="text" name="vehicle" class="form-control" disabled /></div>
            </div>
            <div class="form-group row">
                <label for="category" class="col-md-3 top-pad">Violation Type:</label>
                <div class="col-md-9">
                    <select id="category" class="form-control">
                        <option value="Unknown"></option>
                    </select>
                </div>
            </div>
            <div class="form-group row">
                <label for="county" class="col-md-3 top-pad">Violation Date:</label>
                <div class="col-md-9"><input id="trafficDate" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="trafficTime" class="col-md-3 top-pad">Violation Time:</label>
                <div class="col-md-9"><input type="time" id="trafficTime" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="photo" class="col-md-3 top-pad">Photo Available:</label>
                <div class="col-md-9">
                    <select id="photo" class="form-control">
                        <option value="No">No</option>
                        <option value="Yes">Yes</option>
                    </select>
                </div>
            </div>
            <div class="form-group row">
                <label for="photo" class="col-md-3 top-pad">Video Available:</label>
                <div class="col-md-9">
                    <select id="video" class="form-control">
                        <option value="No">No</option>
                        <option value="Yes">Yes</option>
                    </select>
                </div>
            </div>
            <div class="form-group row">
                <label for="pdd" class="col-md-3 top-pad">Payment Due Date:</label>
                <div class="col-md-9"><input id="pdd" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="pmtDate" class="col-md-3 top-pad">Payment Date:</label>
                <div class="col-md-9"><input id="pmtDate" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="pmtAmt" class="col-md-3 top-pad">Payment Amount:</label>
                <div class="col-md-9"><input type="text" id="pmtAmt" class="form-control" /></div>
            </div>
        </div>
        <p class="text-center"><input type="button" id="btnUpdateViolation" class="btn btn-primary" value="Update Violation/Ticket" /></p>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations", "Index") ::
        @Html.ActionLink("Process New Violation", "Create") ::
        @Html.ActionLink("Traffic Violation Details", "Details") ::
        @Html.ActionLink("Scrap Traffic Violation", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                url: "/api/ViolationTypes",
                method: "GET",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (index, category) {
                        $("#category").append("<option value = '" + category["ViolationName"] + "'>" +
                            category["ViolationName"] + "</option>");
                    });
                }
            });
    
            $("#btnLocateViolation").click(function (event) {
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url:      "/api/TrafficViolations/" + $("#infractionId").val(),
                    success: function (data) {
                        $("#cmrNbr").val(data.CameraNumber);
                        $("#tagNbr").val(data.TagNumber);
                        if (data.ViolationName === "Speed") {
                            $("#category").val("Speed");
                        }
                        else {
                            $("#category").val(data.ViolationName);
                        }
                        $("#trafficDate").val(data.ViolationDate);
                        $("#trafficTime").val(data.ViolationTime);
                        $("#photo").val(data.PhotoAvailable);
                        $("#video").val(data.VideoAvailable);
                        $("#pdd").val(data.PaymentDueDate);
                        $("#pmtDate").val(data.PaymentDate);
                        $("#pmtAmt").val(data.PaymentAmount);
                    }
                });
    
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url:      "/api/Cameras",
                    success: function (data) {
                        $.each(data, function (index, device) {
                            if (device["CameraNumber"] === $("#cmrNbr").val()) {
                                $(".camera-details").val(device["Make"] + " " +
                                    device["Model"] + " (Location: " +
                                    device["Location"] + ")");
                            }
                        });
                    }
                });
    
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url:      "/api/Vehicles",
                    success: function (data) {
                        $.each(data, function (index, car) {
                            if (car["TagNumber"] === $("#tagNbr").val()) {
                                $("input[name='vehicle']").val(car["Make"] + " " +
                                    car["Model"] + " (" +
                                    car["VehicleYear"] + ", " + car["Color"] + ")");
                            }
                        });
                    }
                });
            });
    
            $("#btnUpdateViolation").click(function (event) {
                var ticket = {
                    TrafficViolationId: $("#infractionId").val(),
                    CameraNumber:       $("#cmrNbr").val(),
                    TagNumber:          $("#tagNbr").val(),
                    ViolationName:      $("#category").val(),
                    ViolationDate:      $("#trafficDate").val(),
                    ViolationTime:      $("#trafficTime").val(),
                    PhotoAvailable:     $("#photo").val(),
                    VideoAvailable:     $("#video").val(),
                    PaymentDueDate:     $("#pdd").val(),
                    PaymentDate:        $("#pmtDate").val(),
                    PaymentAmount:      $("#pmtAmt").val()
                };
                $.ajax({
                    data:   ticket,
                    method: "PUT",
                    url:    "/api/TrafficViolations/" + $("#infractionId").val(),
                    success: function (data) {
                        alert("The information about the violation has been updated.")
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>

Deleting a Record

Deleting a record consists of removing it from its table. To assist you in deleting a record in a Web API class, Microsoft Visual Studio creates a method whose name starts with Delete... It takes one argument. Here is an example:

. . .

namespace TrafficTicketsSystem1.TrafficControllers
{
    public class CamerasController : ApiController
    {
        private TicketsModel db = new TicketsModel();

        . . .

        // DELETE: api/Cameras/5
        [ResponseType(typeof(Camera))]
        public IHttpActionResult DeleteCamera(int id)
        {
            Camera camera = db.Cameras.Find(id);
            if (camera == null)
            {
                return NotFound();
            }

            db.Cameras.Remove(camera);
            db.SaveChanges();

            return Ok(camera);
        }

        . . .
    }
}

This method takes an argument that can uniquely identify the record that must be deleted. The database context would look for a record that has that value in its primary key. If it finds it, it deletes it and saves the table.

The HTML verb used to remove a record is called DELETE. You can use it when creating an object to pass to an $.ajax() object.

Practical LearningPractical Learning: Using a Local Object

  1. In the Solution Explorer, under Controllers, double-click VehiclesController.cs to access the file
  2. In the document, right-click one of the Delete() methods and click Add View...
  3. In the Add View dialog box, make sure the View Name text box displays Delete. Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Remove Vehicle Registration";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Revoke Vehicle Registration</h2>
    
    <form name="TrafficCamera" method="post">
        <div class="traffic-holder">
            <div class="form-group row">
                <label for="carId" class="col-md-3 top-pad">Vehicle Id:</label>
                <div class="col-md-3"><input type="text" name="carId" class="form-control small" /></div>
                <div class="col-md-3">
                    <input type="button" name="btnFindVehicleRegistration" class="btn btn-primary" value="Find Vehicle Registration" />
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Vehicle Tag #:</label>
                <div class="col-md-9"><span name="tagNbr"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Owner Drv. Lic. #:</label>
                <div class="col-md-9"><span name="dln"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Make:</label>
                <div class="col-md-9"><span name="manufacturer"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Model:</label>
                <div class="col-md-9"><span name="model"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Year:</label>
                <div class="col-md-9"><span name="yr"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Color:</label>
                <div class="col-md-9"><span name="color"></span></div>
            </div>
        </div>
        <p class="text-center"><input type="button" name="btnRevokeRegistration" class="btn btn-primary" value="Revoke Vehicle Registration" /></p>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Vehicles Registrations", "Index") :: ::
        @Html.ActionLink("Create Vehicle Registration", "Create")
        @Html.ActionLink("Vehicle Registration Details", "Details") ::
        @Html.ActionLink("Edit/Update Vehicle Registration", "Edit")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("input[value='Find Vehicle Registration']").on("click", function (event) {
                $.ajax({
                    url:      "/api/Vehicles/" + $("input[name='carId']").val(),
                    method:   "GET",
                    dataType: "json",
                    success: function (data) {
                        $("span[name='tagNbr']").text(data.TagNumber);
                        $("span[name='dln']").text(data.DrvLicNumber);
                        $("span[name='manufacturer']").text(data.Make);
                        $("span[name='model']").text(data.Model);
                        $("span[name='yr']").text(data.VehicleYear);
    
                        $("span[name='color']").text(data.Color);
                    }
                });
            });
    
            $("input[value='Revoke Vehicle Registration']").on("click", function (event) {
                var car = {
                    VehicleID:    $("input[name='carId']").val(),
                    TagNumber:    $("span[name='tagNbr']").val(),
                    DrvLicNumber: $("span[name='dln']").val(),
                    Make:         $("span[name='manufacturer']").val(),
                    Model:        $("span[name='model']").val(),
                    VehicleYear:  $("span[name='yr']").val(),
                    Color:        $("span[name='color']").val()
                };
                $.ajax({
                    data:   car,
                    method: "DELETE",
                    url:    "/api/Vehicles/" + $("input[name='carId']").val(),
                    success: function (data) {
                        alert("The vehicle registration has been cancelled.")
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>
  5. In the Solution Explorer, under Views, right-click Drivers -> Add -> View...
  6. Type Delete as the name of the view
  7. Click Add
  8. Change the document as follows:
    @{
        ViewBag.Title = "Delete Driver";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Delete Driver's Record</h2>
    
    <form name="TrafficCamera" method="post">
        <div class="vehicle-holder">
            <div class="form-group row">
                <label for="driverId" class="col-md-3 top-pad">Driver ID:</label>
                <div class="col-md-3"><input type="text" id="driverId" class="form-control small" /></div>
                <div class="col-md-3">
                    <input type="button" name="btnFindDriver" class="btn btn-primary" value="Find Driver's Record" />
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Drv. Lic. #:</label>
                <div class="col-md-9"><span id="dln"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">First Name:</label>
                <div class="col-md-9"><span id="fname"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Last Name:</label>
                <div class="col-md-9"><span id="lname"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Address:</label>
                <div class="col-md-9"><span name="adrs"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">City:</label>
                <div class="col-md-9"><span name="city"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">County:</label>
                <div class="col-md-9"><span name="county"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">State:</label>
                <div class="col-md-9"><span name="state"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">ZIP-Code:</label>
                <div class="col-md-9"><span name="zip"></span></div>
            </div>
        </div>
        <p class="text-center"><input type="button" name="btnRevokeRegistration" class="btn btn-primary" value="Revoke Vehicle Registration" /></p>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Drivers/Owners", "Index") :: ::
        @Html.ActionLink("Create Drivers/Owner Record", "Create")
        @Html.ActionLink("Driver/Owner Details", "Details") ::
        @Html.ActionLink("Edit/Update Driver/Owner Information", "Edit")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("input[class='btn btn-primary']").on("click", function (event) {
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url:      "/api/Drivers/" + $("input[id='driverId']").val(),
                    success: function (data) {
                        $("span[id='dln']").text(data.DrvLicNumber);
                        $("span[id='fname']").text(data.FirstName);
                        $("span[id='lname']").text(data.LastName);
                        $("span[name='adrs']").text(data.Address);
                        $("span[name='city']").text(data.City);
                        $("span[name='county']").text(data.County);
                        $("span[name='state']").text(data.State);
                        $("span[name='zip']").text(data.ZIPCode);
                    }
                });
            });
    
            $("input[value='Revoke Vehicle Registration']").on("click", function (event) {
                var car = {
                    DriverID:     $("input[class='form-control small']").val(),
                    DrvLicNumber: $("span[id='dln']").val(),
                    FirstName:    $("span[id='fname']").val(),
                    LastName:     $("span[id='lname']").val(),
                    Address:      $("span[name='adrs']").val(),
                    City:         $("span[name='city']").val(),
                    County:       $("span[name='county']").val(),
                    State:        $("span[name='state']").val(),
                    ZIPCode:      $("span[name='zip']").val()
                };
                $.ajax({
                    data:   car,
                    method: "DELETE",
                    url: "/api/Drivers/" + $("input[class='form-control small']").val(),
                    success: function (data) {
                        alert("The driver's record has been deleted.")
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>
  9. In the Solution Explorer, under Views, right-click Cameras -> Add -> View...
  10. Type Delete
  11. Click Add
  12. Change the document as follows:
    @{
        ViewBag.Title = "Remove Traffic Camera";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Traffic Camera Removal</h2>
    
    <form name="TrafficCamera" method="post">
        <div class="box-holder">
            <div class="form-group row">
                <label for="cameraId" class="col-md-3 top-pad">Camera Id:</label>
                <div class="col-md-3"><input type="text" id="cameraId" class="form-control small" /></div>
                <div class="col-md-3">
                    <input type="button" id="btnFindRecord" class="btn btn-primary" value="Find Camera" />
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Camera #:</label>
                <div class="col-md-9"><span id="cameraNumber"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Make:</label>
                <div class="col-md-9"><span id="make"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Model:</label>
                <div class="col-md-9"><span id="model"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Location:</label>
                <div class="col-md-9"><span id="location"></span></div>
            </div>
        </div>
        <p class="text-center"><input type="button" id="btnDeleteRecord" class="btn btn-primary" value="Remove Traffic Camera" /></p>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Traffic Cameras", "Index") ::
        @Html.ActionLink("New Traffic Camera", "Create") ::
        @Html.ActionLink("Traffic Camera Details", "Details") ::
        @Html.ActionLink("Edit/Update Camera Information", "Edit")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnFindRecord").click(function (event) {
                $.ajax({
                    url: "/api/Cameras/" + $("#cameraId").val(),
                    method: "GET",
                    dataType: "json",
                    success: function (data) {
                        $("#cameraId").val(data.CameraId);
                        $("#cameraNumber").text(data.CameraNumber);
                        $("#make").text(data.Make);
                        $("#model").text(data.Model);
                        $("#location").text(data.Location);
                    }
                });
            });
    
            $("#btnDeleteRecord").click(function (event) {
                var camera = {
                    CameraID:     $("#cameraId").val(),
                    CameraNumber: $("#cameraNumber").val(),
                    Make:         $("#make").val(),
                    Model:        $("#model").val(),
                    Location:     $("#location").val()
                };
                $.ajax({
                    url: "/api/Cameras/" + $("#cameraId").val(),
                    method: "DELETE",
                    data: camera,
                    success: function (data) {
                        alert("The traffic camera record has been removed.")
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>
  13. In the Solution Explorer, under Views, right-click TrafficViolations -> Add -> View...
  14. Type Delete as the name of the view
  15. Click Add
  16. Change the document as follows:
    @{
        ViewBag.Title = "Violation/Infraction Details";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Violation/Infraction Details</h2>
    
    <form name="DriverOwner" method="post">
        <div class="vehicle-holder">
            <div class="form-group row">
                <label for="cameraId" class="col-md-3 top-pad">Violation Id:</label>
                <div class="col-md-3"><input type="text" id="infractionId" class="form-control small" /></div>
                <div class="col-md-3">
                    <input type="button" id="btnShowViolation" class="btn btn-primary" value="Show the Violation" />
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Camera:</label>
                <div class="col-md-8"><span name="capturingCamera"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Vehicle Tag #:</label>
                <div class="col-md-8"><span name="violatingVehicle"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Violation Type:</label>
                <div class="col-md-8"><span name="InfrationCategory" /></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Violation Date:</label>
                <div class="col-md-8"><span name="date-of-infraction"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Violation Time:</label>
                <div class="col-md-8"><span name="time-of-infraction"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Photo is Available:</label>
                <div class="col-md-8"><span name="steady-photo-available"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Video is Available:</label>
                <div class="col-md-8"><span name="streaming-video-available"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Payment Due Date:</label>
                <div class="col-md-8"><span name="payment due date"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Payment Date:</label>
                <div class="col-md-8"><span name="last-day-payment"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-4">Amount Owed:</label>
                <div class="col-md-8"><span name="amount-owed"></span></div>
            </div>
        </div>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations", "Index") ::
        @Html.ActionLink("New Traffic Violation", "Create") ::
        @Html.ActionLink("Edit/Update Traffic Violation", "Edit") ::
        @Html.ActionLink("Delete/Cancel Traffic Violation", "Delete")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $(".btn-primary").on("click", function (event) {
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url: "/api/TrafficViolations/" + $("#infractionId").val(),
                    success: function (data) {
                        $("span[name$='Camera']").text(data.CameraNumber);
                        $("span[name$='Vehicle']").text(data.TagNumber);
                        $("span[name$='Category']").text(data.ViolationName);
                        $("span[name|='date']").text(data.ViolationDate);
                        $("span[name|='time']").text(data.ViolationTime);
                        $("span[name*='photo']").text(data.PhotoAvailable);
                        $("span[name*='video']").text(data.VideoAvailable);
                        $("span[name~='due']").text(data.PaymentDueDate);
                        $("span[name='last-day-payment']").text(data.PaymentDate);
                        $("span[name='amount-owed']").text(data.PaymentAmount);
                    }
                });
            });
        });
    </script>
  17. In the Solution Explorer, under Views, right-click ViolationsTypes -> Add -> View...
  18. Type Delete as the name of the view
  19. Click Add
  20. Change the document as follows:
    @{
        ViewBag.Title = "Delete Violation Type";
    }
    
    <h2 class="text-center bold common-font blue bottom-border">Delete Violation Type</h2>
    
    <form name="TrafficCamera" method="post">
        <div class="traffic-holder">
            <div class="form-group row">
                <label for="violationTypeId" class="col-md-3 top-pad">Violation Type Id:</label>
                <div class="col-md-3"><input type="text" id="violationTypeId" class="form-control small" /></div>
                <div class="col-md-3">
                    <input type="button" id="btnGetViolationType" class="btn btn-primary" value="Get Violation Type" />
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Volation Type:</label>
                <div class="col-md-9"><span id="vType"></span></div>
            </div>
            <div class="form-group row">
                <label class="col-md-3">Description:</label>
                <div class="col-md-9"><span id="describe"></span></div>
            </div>
        </div>
        <p class="text-center"><input type="button" name="btnRevokeRegistration" class="btn btn-primary" value="Revoke Vehicle Registration" /></p>
    </form>
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations Types", "Index") ::
        @Html.ActionLink("New Violation Type", "Create") ::
        @Html.ActionLink("Description of a Violation Type", "Details") ::
        @Html.ActionLink("Edit/Update Violation Type", "Edit")
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnGetViolationType").on("click", function (event) {
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url:      "/api/ViolationTypes/" + $("#violationTypeId").val(),
                    success: function (data) {
                        $("#violationTypeId").val(data.ViolationTypeId);
                        $("#vType").text(data.ViolationName);
                        $("#describe").text(data.Description);
                    }
                });
            });
    
            $("input[value='Revoke Vehicle Registration']").on("click", function (event) {
                var car = {
                    ViolationTypeId: $("#violationTypeId").val(),
                    ViolationName: $("#vType").text(),
                    Description: $("#describe").text()
                };
                $.ajax({
                    data: car,
                    method: "DELETE",
                    url: "/api/ViolationTypes/" + $("#violationTypeId").val(),
                    success: function (data) {
                        alert("The violation type has been removed from our system.")
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>
  21. To execute, on the main menu, click Debug -> Start Without Debugging
  22. Click the Cameras link

    ASP.NET MVC - Web API - Traffic Tickets Management

  23. Click the New Traffic camera link:

    ASP.NET MVC - Web API - Traffic Tickets Management

  24. Create a few records as follows:

    ASP.NET MVC - Web API - Traffic Tickets Management

    Camera # Make Model Location
    DGH-38460 Ashton Digital MPH-6000 Eastern Ave and Ashburry Drv
    ELQ-79284 Seaside Worldwide BL4500 Monroe Str and Westview Rd
    FKD-2040 Random Selection RDS-2040 Amoros Cross Road
    MSR-59575 Ashton Digital MPH-6000 Concordia Blvd and Sunset Way
    DHT-29417 Woodson and Sons NG200 Temple Ave and Barclay Rd
    AHR-41518 Seaside International 442i Chesterwood Rd and Old Dutler Str
    HTR-93847 Ashton Digital 366d Monrovia Str at Moon Springs

    ASP.NET MVC - Web API - Records

  25. Click Edit/Update Camera Information

    ASP.NET MVC - Web API - Editing and Updating a Record

  26. In the top Camera ID text box, type 2
  27. Click the Find Camera button

    ASP.NET MVC - Web API - Editing and Updating a Record

  28. Change the following values:
    Make:  Seaside International
    Model: BL5

    ASP.NET MVC - Web API - Editing and Updating a Record

  29. Click Update Camera Details

    ASP.NET MVC - Web API - Editing and Updating a Record

  30. Click OK on the message box

    ASP.NET MVC - Web API - Records

  31. Click the Remove Camera link

    ASP.NET MVC - Web API - Creatinga New Record

  32. In the Camera ID text box, type 3
  33. Click the Find Camera button

    ASP.NET MVC - Web API - Creatinga New Record

  34. Click the Remove Traffic Camera button

    ASP.NET MVC - Web API - Creatinga New Record

  35. Click OK on the message box

    ASP.NET MVC - Web API - Records

  36. Click the Violations Types link
  37. Click New Violation Type:

    ASP.NET MVC - Web API - Creatinga New Record

  38. Create the following violations types:
       
    Violation Types Description
    Speed Drivers are required to drive at, or below, the posted speed limit.
    Stop Sign A driver is required to come to a complete stop at the Stop sign, even there is no other vehicle on the other street(s).
    Red Light Steady A vehicle must completely stop when the light is red.
    Red Light Flashing If a vehicle comes to an intersection that has a flashing red light, the vehicle must first stop completely, before proceeding.
    Red Light Right Turn If a vehicle must make a right turn where the red light is steady, the vehicle must first completely stop before proceeding.

    ASP.NET MVC - Web API and Using Virtual Members

  39. Click the Drivers/Owners link
  40. Click the New Driver/Owner link

    ASP.NET MVC - Web API - Creatinga New Record

  41. Create a few records as follows:
       
    Drv. Lic # First Name Last Name Address City County State ZIP-Code
    26 840 681 Simon Havers 1884 Stewart Ln Kittanning Armstrong PA 15638
    273-79-4157 Terence McConnell 8304 Polland Str Meadowview Washington VA 24361
    A402-630-468 Patrick Atherton 10744 Quincy Blvd Cumberland Allegany MD 21502
    C-684-394-527 Sarah: Cuchchran 10804 Euton Rd Shawnee Land   VA 24450
    928-37-4950 Michael Atherton 663 Vernon Drv, NW Washington    DC 20012
    2938468 Victoria Huband 3958 Lubber Court Middletown New Castle DE 19709
    851608526 Patrick Whalley 10227 Woodrow Rd Shelbyville Bedford TN 38561
    W639-285-940 David Woodbank 9703 Abington Ave Hurlock Dorchester MD 21643
    S-283-942-646 Emilie Sainsbury 4048 Utah Rd Denville Morris NJ 07961
    860586175 Kelley Murray 8622 Rutger Farms Str Rutger Farms Macon TN 37122
    INSERT Drivers(DrvLicNumber, FirstName, LastName, [Address], City, County, [State], ZIPCode)
    VALUES(N'26 840 681',   N'Simon',   N'Havers',    N'1884 Stewart Ln',   N'Kittanning', N'Armstrong',  N'PA', N'15638'),
          (N'273-79-4157',  N'Terence', N'McConnell', N'8304 Polland Str',  N'Meadowview', N'Washington', N'VA', N'24361'),
          (N'A402-630-468', N'Patrick', N'Atherton',  N'10744 Quincy Blvd', N'Cumberland', N'Allegany',   N'MD', N'21502');
    GO
    INSERT Drivers(DrvLicNumber, FirstName, LastName, [Address], City, [State], ZIPCode)
    VALUES(N'C-684-394-527', N'Sarah',   N'Cuchchran', N'10804 Euton Rd',     N'Shawnee Land', N'VA', N'24450'),
          (N'928-37-4950',   N'Michael', N'Atherton',  N'663 Vernon Drv, NW', N'Washington',   N'DC', N'20012');
    GO
    INSERT Drivers(DrvLicNumber, FirstName, LastName, [Address], City, County, [State], ZIPCode)
    VALUES(N'293846',        N'Victoria', N'Huband',    N'3958 Lubber Court',     N'Middletown',   N'New Castle', N'DE', N'19709'),
          (N'851608526',     N'Patrick',  N'Whalley',   N'10227 Woodrow Rd',      N'Shelbyville',  N'Bedford',    N'TN', N'38561'),
          (N'W639-285-940',  N'David',    N'Woodbank',  N'9703 Abington Ave',     N'Hurlock',      N'Dorchester', N'MD', N'21643'),
          (N'S-283-942-646', N'Emilie',   N'Sainsbury', N'4048 Utah Rd',          N'Denville',     N'Morris',     N'NJ', N'07961'),
          (N'860586175',     N'Kelley',   N'Murray',    N'8622 Rutger Farms Str', N'Rutger Farms', N'Macon',      N'TN', N'37122');
    GO

    ASP.NET MVC - Web API and Using Virtual Members

  42. Click the Vehicles link:

  43. Click the New Vehicle Registration link

    ASP.NET MVC - Web API - Creatinga New Record

  44. Create a few records using the following values:

    ASP.NET MVC - Web API - Creatinga New Record

    Tag # Drv. Lic. # Make Model Vehicle Year Color
    8DE9275 26 840 681 Ford Focus 2000 Gray
    KLT4805 293846 Toyota Corolla 2016 Red
    KAS9314 W639-285-940 Cadillac Escalade 2008 Black
    HAK3936 S-283-942-646 Chrysler Crossfire 2006 Red
    PER2849 26 840 681 Buick LeSabre 2012 Silver
    MWH4685 851608526 Honda Accord 1998 Blue
    971384 928-37-4950 BMW 325i 2015 White
    394815 273-79-4157 Jeep Wrangler 1996 Black

  45. Show the details for the third vehicle:

    Text Box

    Text Box

  46. Click Traffic Tickets

  47. Click the New Traffic Violation link

    ASP.NET MVC - Web API - Creating a New Record

  48. Create some records using the following values:

    ASP.NET MVC - Web API - Creating a New Record

    ASP.NET MVC - Web API - Creating a New Record

    Camera # Tag # Violation Name Violation Date Violation Time Photo Available Video Available Payment Due Date Payment Amount
    MSR-59575 KLT4805 Stop Sign 2018-01-18 09:12:35 No Yes 2018-02-28 75
    DHT-29417 971384 Speed 2018-02-06 11:58:06 No Yes 2018-04-05 85
    DGH-38460 PER2849 Red Light Steady 2018-01-31 05:15:18 Yes No 2018-03-10 125
    DHT-29417 MWH4685 Speed 2018-03-05 16:07:15 Yes Yes 2018-04-22 85
    MSR-59575 8DE9275 Stop Sign 2018-01-18 14:22:48 No Yes 2018-03-10 60
    ELQ-79284 KLT4805 Speed 2018-04-12 08:16:22 No Yes 2018-06-08 100
    HTR-93847 PER2849 Red Light Flashing 2018-01-28 22:14:53 No No 2018-03-02 45
    AHR-41518 MWH4685 Speed 2018-03-31 22:07:31 Yes No 2018-05-15 75
    DGH-38460 KAS9314 Red Light Right Turn 2018-01-31 12:30:11 Yes No 2018-02-28 60
    DHT-29417 971384 Speed 2018-02-06 19:04:47 Yes Yes 2018-04-05 85
    ELQ-79284 8DE9275 Speed 2018-04-15 15:25:53 Yes No 2018-06-02 40

  49. Update the following records:

    Violation Id Payment Date Payment Amount
    10 85 2018-03-31
    3 125 2018-03-02
    8 105 2018-06-08
    1 75 2018-02-26
    5 60 2018-02-27
    6 150 2018-07-08

  50. Close the browser and return to your programming environment
  51. Close your programming environment

Previous Copyright © 2017-2022, FunctionX Home