An Application for Traffic Tickets

Introduction

ASP.NET offers one of the means of creating a Web-based application. One of the available options is ASP.NET MVC. One of the shortcomings of ASP.NET MVC is that it doesn't support events such as when a text box loses focus. To handle such events, you can use JavaScript or one of its libraries. For this exercise, we use use jQuery.

Practical LearningPractical Learning: Introducing the Application

  1. Start Microsoft Visual Studio
  2. In the Visual Studio 2022 dialog box, click Create a New Project
  3. In the languages combo box, select C#.
    In the list of projects templates, click ASP.NET Web Application (.NET Framework)
  4. Click Next
  5. Change the project Name to TrafficTicketsSystem1.
    Access or change the contents of the Location text box.
    In the Framework combo box, select the highest (.NET Framework 4.8)
  6. Click Create
  7. In the Create a New ASP.NET Web Application dialog box, click the Web API icon
  8. Click Create
  9. In the Solution Explorer, right-click TrafficTicketsSystem1 -> Add -> New Folder
  10. Type Images
  11. Copy and paste the following pictures to the Images folder:

    Traffic Tickets System Traffic Tickets System
    Chair
  12. In the Solution Explorer, double-click Content to expand it
  13. Below Content, double-click Site.css
  14. Add the following styless:
    /* Set padding to keep content from hitting the edges */
    .body-content {
        margin-top: 15px;
        padding-left: 15px;
        padding-right: 15px;
    }
    
    /* Set width on the form input elements since they're 100% wide by default */
    input,
    select,
    textarea {
        max-width: 280px;
    }
    
    .bg-maroon         { --bs-bg-opacity:  1;
                         background-color: maroon !important;                           }
    .border-bottom     { border-bottom:    1px solid gray !important;                   }
    .card              { border:           1px solid #404080;                           }
    .marginer          { margin-left:      10px;
                         margin-right:     10px;                                        }
    .shadow-md         { box-shadow:       0.65rem 0.65rem 0.65rem #808080 !important;  }
    .nav-link          { color:            white;
                         font-family:      Georgia, Garamond, 'Times New Roman', serif; }
    .nav-link:hover,
    .nav-link:focus    { color:            yellow;                                      }
    .nav-link.disabled { color:            black;                                       }
    .common-font       { font-family:      Georgia, Garamond, 'Times New Roman', serif; }
    .box-holder        { margin:           auto;
                         width:            450px;                                       }
    .top-padding       { padding-top:      0.40em;                                      }
    .col-md-36         { width:            36%;
                         flex:             0 0 auto;                                    }
    .col-md-64         { width:            64%;
                         flex:             0 0 auto;                                    }
    .col-md-32         { width:            32%;
                         flex:             0 0 auto;                                    }
    .tts-nav           { color:            blue;
                         text-decoration:  none;
                         font-family:      Georgia, Garamond, 'Times New Roman', serif; }
    .tts-nav:link      { color:            blue;                                        }
    .tts-nav:visited   { color:            tomato;                                      }
    .tts-nav:active    { color:            #A8C3CE;                                     }
    .tts-nav:hover     { color:            maroon;                                      }
  15. In the Solution Explorer, under Views, expand Shared and click _Layout.cshtml
  16. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width" />
        <title>Traffic Tickets System - @ViewBag.Title</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-dark bg-maroon">
            <div class="container">
                @Html.ActionLink("Traffic Tickets System", "Index", "Home", new { area = "" }, new { @class = "navbar-brand common-font" })
                <button type="button" class="navbar-toggler" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" title="Toggle navigation" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse d-sm-inline-flex justify-content-between">
                    <ul class="navbar-nav flex-grow-1">
                        <li>@Html.ActionLink("Traffic Violations", "Index", "Traffic Violations", new { area = "" }, new { @class = "nav-link" })</li>
                        <li>@Html.ActionLink("Cameras",          "Index", "Camera", new { area = "" }, new { @class = "nav-link" })</li>
                        <li>@Html.ActionLink("Drivers",          "Index", "Driver", new { area = "" }, new { @class = "nav-link" })</li>
                        <li>@Html.ActionLink("Vehicles",         "Index", "Vehicle", new { area = "" }, new { @class = "nav-link" })</li>
                        <li>@Html.ActionLink("Violations Types", "Index", "ViolationsTypes", new { area = "" }, new { @class = "nav-link" })</li>
                        <li>@Html.ActionLink("API",              "Index", "Help", new { area = "" }, new { @class = "nav-link" })</li>
                    </ul>
                </div>
            </div>
        </nav>
        <div class="container body-content">
            @RenderBody()
            <hr />
            <footer>
                <p class="text-center common-font">&copy; 2011-@DateTime.Now.Year - Traffic Tickets System</p>
            </footer>
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  17. In the Solution Explorer, under Views, expand Home and double-click Index.cshtml
  18. Change the document as follows:
    <main>
        <section class="row">
            <h1 class="text-center fw-bold text-capitalize common-font">Traffic Tickets System</h1>
            <p class="lead text-center common-font">The Solomon County Police Department is a division of the Solomon County government. This department is proud to insure the safety, security, and wellbeing of both our citizens and our visitors.</p>
        </section>
        <hr />
        <div class="row common-font">
            <section class="col-md-4" aria-labelledby="government">
                <div class="card shadow-md">
                    <p><img src="~/Images/Government.png" style="width: 100%; height: 225px;" /></p>
                    <h2 class="fw-bold text-capitalize border-bottom marginer">government</h2>
                    <p class="marginer">Citizens and visitors can get more information about the available services and duties.</p>
                </div>
            </section>
            <section class="col-md-4" aria-labelledby="communityServices">
                <div class="card shadow-md">
                    <p><img src="~/Images/Community.png" style="width: 100%; height: 225px;" /></p>
                    <h2 class="fw-bold text-capitalize border-bottom marginer">community services</h2>
                    <p class="marginer">Here you can find more information about public parks (recreatiional parks, etc).</p>
                </div>
            </section>
            <section class="col-md-4" aria-labelledby="publicInformation">
                <div class="card shadow-md">
                    <p><img src="~/Images/Relations.png" style="width: 100%; height: 225px;" /></p>
                    <h2 class="fw-bold text-capitalize border-bottom marginer">public information</h2>
                    <p class="marginer">Here is information about our activities, how we operate, and our future projects.</p>
                </div>
            </section>
        </div>
    </main>

Creating a Database

Our Traffic Tickets System application needs a database. We will create it as a Microsoft SQL Server database. To use it in jQuery, we will use the Entity Framework to take advantage of the Web API.

Practical LearningPractical Learning: Creating a Database

  1. To create a local database, in the Solution Explorer of Microsoft Visual Studio, right-click App_Data -> Add -> New Item...
  2. In the middle frame of the Add New Item dialog box, click SQL Server Database.
    Change the Name to TrafficTicketsSystem1
  3. Click Add
  4. In the Solution Explorer, under App_Data, right-click TrafficTicketsSystem1 and click Open
  5. In the Server Explorer, right-click TrafficTicketsSystem1 and click New Query
  6. 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(120),
        City                   NVARCHAR(50),
        County                 NVARCHAR(50),
        [State]                NVARCHAR(40),
        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            NVARCHAR(5),
        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),
        TrafficViolationNumber NVARCHAR(12),
        CameraNumber           NVARCHAR(20),
        TagNumber              NVARCHAR(20),
        ViolationName          NVARCHAR(30),
        ViolationDate          NVARCHAR(40),
        ViolationTime          NVARCHAR(40),
        PhotoAvailable         NVARCHAR(10),
        VideoAvailable         NVARCHAR(10),
        PaymentDueDate         NVARCHAR(40),
        PaymentDate            NVARCHAR(40),
        PaymentAmount          NVARCHAR(10),
        PaymentStatus          NVARCHAR(25),
        CONSTRAINT PK_Violations PRIMARY KEY(TrafficViolationId)
    );
    GO
  7. To execute, on the SQL Editor toolbar, click the Execute button Execute
  8. Close the Query window
  9. When asked whether you want to save, click No
  10. In the Solution Explorer, right-click Models -> Add -> New Item...
  11. In the left frame of the dialog box, click Data and, in the middle frame, click ADO.NET Entity Data Model
  12. Change the name to TicketsManagementModel

    Add New Item

  13. Click Add
  14. In the first page of the Entity Data Model Wizard, click Code First From Database

    Entity Data Model Wizard

    Click Next
  15. In the second page of the Entity Data Model Wizard, click the arrow of the top combo box and select TrafficTicketsSystem1.mdf.
    Make sure the bottom text box displays TicketsManagementModel

    Entity Data Model Wizard

    Click Next
  16. In the third page of the Entity Data Model Wizard, click the Tables check box:

    Entity Data Model Wizard

  17. Click Finish
  18. On the main menu, click Debug -> Start Without Debugging:

    Traffic Tickets System

Violations Types

A List of Violations Types

Different countries, different states, differents counties, and different jurisdictions have different laws or various views on what constitutes a traffic violation. To represent the categories of violations that a vehicle can comit, as seen above in our database, our application will provide the ability to display a list of types of traffic violation. For this exercise, our application will use just a sample list.

Practical LearningPractical Learning: Displaying Violations Types

  1. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  2. In the left list of the Add New Scaffolded Item dialog box, click Web API
  3. In the middle list, click Web API 2 Controller With Actions, Using Entity Framework

    Add New Scaffolded Item

  4. Click Add
  5. Click the arrow of the Model Class combo box and select ViolationType (TrafficTicketsSystem1.Models)
  6. Click the arrow of the Data Context Class combo box and select TicketsManagementModel (TrafficTicketsSystem1.Models)
  7. Make sure the Controller Name text box is displaying ViolationTypesController:

    Add Controller

    Click Add:
    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 ViolationTypesController : ApiController
        {
            private TicketsManagementModel db = new TicketsManagementModel();
    
            // GET: api/ViolationTypes
            public IQueryable<ViolationType> GetViolationTypes()
            {
                return db.ViolationTypes;
            }
    
            // GET: api/ViolationTypes/5
            [ResponseType(typeof(ViolationType))]
            public IHttpActionResult GetViolationType(int id)
            {
                ViolationType violationType = db.ViolationTypes.Find(id);
                if (violationType == null)
                {
                    return NotFound();
                }
    
                return Ok(violationType);
            }
    
            // PUT: api/ViolationTypes/5
            [ResponseType(typeof(void))]
            public IHttpActionResult PutViolationType(int id, ViolationType violationType)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
                if (id != violationType.ViolationTypeId)
                {
                    return BadRequest();
                }
    
                db.Entry(violationType).State = EntityState.Modified;
    
                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ViolationTypeExists(id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
    
                return StatusCode(HttpStatusCode.NoContent);
            }
    
            // POST: api/ViolationTypes
            [ResponseType(typeof(ViolationType))]
            public IHttpActionResult PostViolationType(ViolationType violationType)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
                db.ViolationTypes.Add(violationType);
                db.SaveChanges();
    
                return CreatedAtRoute("DefaultApi", new { id = violationType.ViolationTypeId }, violationType);
            }
    
            // DELETE: api/ViolationTypes/5
            [ResponseType(typeof(ViolationType))]
            public IHttpActionResult DeleteViolationType(int id)
            {
                ViolationType violationType = db.ViolationTypes.Find(id);
                if (violationType == null)
                {
                    return NotFound();
                }
    
                db.ViolationTypes.Remove(violationType);
                db.SaveChanges();
    
                return Ok(violationType);
            }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }
    
            private bool ViolationTypeExists(int id)
            {
                return db.ViolationTypes.Count(e => e.ViolationTypeId == id) > 0;
            }
        }
    }
  8. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  9. In the middle list of the Add New Scaffolded Item dialog box, click MVC 5 Controller With Read/Write Actions

    Add New Scaffolded Item

  10. Click Add
  11. In the Controller Name text box of the Add Controller dialog box, replace Default with ViolationsTypes to get ViolationsTypesController

    Add Controller

  12. Click Add
  13. In the Details(), the Edit(), and the Delete() methods, make the id argument nullable:
    using System.Web.Mvc;
    
    namespace TrafficTicketsSystem1.Controllers
    {
        public class ViolationsTypesController : Controller
        {
            // GET: ViolationsTypes
            public ActionResult Index()
            {
                return View();
            }
    
            // GET: ViolationsTypes/Details/5
            public ActionResult Details(int? id)
            {
                return View();
            }
    
            // GET: ViolationsTypes/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: ViolationsTypes/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: ViolationsTypes/Edit/5
            public ActionResult Edit(int? id)
            {
                return View();
            }
    
            // POST: ViolationsTypes/Edit/5
            [HttpPost]
            public ActionResult Edit(int? id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: ViolationsTypes/Delete/5
            public ActionResult Delete(int? id)
            {
                return View();
            }
    
            // POST: ViolationsTypes/Delete/5
            [HttpPost]
            public ActionResult Delete(int id?, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  14. In the ViolationsTypesController class, right-click Index() and click Add View...
  15. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  16. In the Add View dialog box, make sure the View Name text box is displaying Index

    Add View

    Click Add
  17. Change the document as follows:
    @{
        ViewBag.Title = "Traffic Violations Types";
    }
    
    <h2 class="text-center common-font bottom-border fw-bold">Traffic Violations Types</h2>
    
    <hr />
    
    <table class="table table-striped common-font">
        <tr>
            <th class="fw-bold text-center">Violation Type Id</th>
            <th class="fw-bold">Violation Name</th>
            <th class="fw-bold">Description</th>
        </tr>
    </table>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("New Violation Type", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Details on Violation Type", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Violation Type", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Remove Violation Type", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </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>

Creating a Category of Violation

Various administrations treat traffic violations differently. They start by defining what a violation type is. In this section, we will create the objects that create and manage the types of violations.

Practical LearningPractical Learning: Creating Violations Types

  1. Click the ViolationsTypesController.cs tab
  2. In the class, right-click one of the Create() methods and click Add View...
  3. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  4. In the Add View dialog box, make sure the View Name text box is displaying Create

    Add View

    Click Add
  5. Change the document as follows:
    @{
        ViewBag.Title = "Traffic Violation Type";
    }
    
    <h2 class="text-center fw-bold common-font bottom-border">Traffic Violation Type</h2>
    
    <hr />
    
    <form name="frmCreateViolationType" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="vName" class="col-md-4 top-padding">Violation Name:</label>
                <div class="col-md-8"><input type="text" id="vName" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="describe" class="col-md-4 top-padding">Description:</label>
                <div class="col-md-8"><textarea id="describe" rows="10" class="form-control"></textarea></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-6">&nbsp;</label>
                <div class="col-md-6 text-center">
                    <input type="button" id="btnDefineViolationType"
                           class="btn btn-primary" value="Create Violation Type" />
                </div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations Types", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Details on Violation Type", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Violation Type", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Remove Violation Type", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnDefineViolationType").click(function () {
                var violationType = {
                    ViolationName: $("#vName").val(),
                    Description: $("#describe").val()
                };
    
                $.ajax({
                    url: "/api/ViolationTypes",
                    method: "POST",
                    data: violationType,
                    success: function (data) {
                        alert("The violation type has been created and saved.");
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>
  6. Click the ViolationsTypesController.cs tab
  7. To execute, on the main menu, click Debug -> Start Without Debugging

    Traffic Tickets System - Home Page

  8. Click the Violation Types link:

    Traffic Tickets System - Violations Types

  9. Click New Violation Type:

    Traffic Tickets System - Violations Type

  10. Create some records using the following values:

    Traffic Tickets System - Violations Type

    Violation Name Description
    Unknown The violation is not, or cannot be, defined.
    Speed The vehicle drove at a speed significantly above the speed limit. The laws in this state require that every non-emergency and non-utility vehicle drive at or below the posted speed limit (or at or below the default speed regulation where the speed is not clearly posted).
    Stop Sign The vehicle did not stop at the Stop sign. The law in the state indicates that every non-emergency vehicle must completely stop at every Stop sign, regardless of the presence or absence of incoming or adjacent vehicles.
    Red Light Steady A vehicle drives by the red light. The law in our state says that if a vehicle comes by a red light, the driver must stop to wait for the green light.
    Red Light Flashing The vehicle drove through a red light that was flashing (or blinking). The laws in this state require that if a vehicle comes to a flashing red light, whether it is at an intersection or not, the vehicle must first stop completely, the driver must observe around for pedestrians, animals, and other cars, and then proceed cautiously.
    Low Light The car was moving on a low light street.
    Red Light Right Turn The vehicle turned to the right without stopping. The laws in this state require that, when a vehicle reaches a traffic light and wants to make a right turn, if the light is red, regardless of any presence or not of another vehicle or pedestrian, the vehicle must first stop completely, wait a few seconds, and then make the right turn.

    Traffic Tickets System - Violations Types

  11. Return to your programming environment

Getting Information About a Category of Violation

.

Practical LearningPractical Learning: Getting a Violation Type

  1. Click the ViolationsTypesController.cs tab
  2. In the class, right-click Details() and click Add View...
  3. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  4. Make sure the View Name text box is displaying Details

    Add View

    Click Add
  5. Change the document as follows:
    @{
        ViewBag.Title = "Volation Type Details";
    }
    
    <h2 class="text-center fw-bold common-font">Volation Type Details</h2>
    
    <hr />
    
    <form name="frmDetailsVolationType" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="cameraId" class="col-md-36 top-padding">Violation Type Id:</label>
                <div class="col-md-32"><input type="text" id="categoryId" class="form-control" /></div>
                <div class="col-md-32">
                    <input type="button" id="btnFindVolationType" class="btn btn-primary" value="Find Volation Type" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="cameraNumber" class="col-md-36">Violation Type:</label>
                <div class="col-md-64"><input type="text" id="vType" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="describe" class="col-md-36">Description:</label>
                <div class="col-md-64"><textarea id="describe" class="form-control" rows="5"></textarea></div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations Types", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("New Violation Type", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Violation Type", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Exclude Violation Type", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </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>
  6. Click the ViolationsTypesController.cs tab
  7. To execute, on the main menu, click Debug -> Start Without Debugging
  8. Click the Violation Types link:

    Traffic Tickets System - Violations Types

  9. Click Details on Violation Type:

    Traffic Tickets System - Violations Type Details

  10. In the Violation Type Id text box, type 2
  11. Click the Find Violation Type button:

    Traffic Tickets System - Violations Type Details

  12. Return to your programming environment

Updating Information About a Category of Violation

For any reason, an administration can change the name or description of a violation type. To help with this, we will create a form that allows a user to edit or update the details of a category of violation.

Practical LearningPractical Learning: Updating a Violation Type

  1. In the ViolationsTypesController.cs tab, right-click one of the Edit() methods and click Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Edit:

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Edit/Update Violation Type";
    }
    
    <h2 class="text-center fw-bold common-font">Edit/Update Violation Type</h2>
    
    <hr />
    
    <form name="frmEditViolationType" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="cameraId" class="col-md-36 top-padding">Violation Type Id:</label>
                <div class="col-md-32"><input type="text" id="vTypeId" class="form-control" /></div>
                <div class="col-md-32">
                    <input type="button" id="btnSearchType" class="btn btn-primary" value="Find Violation Type" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="category" class="col-md-36 top-padding">Violation Type:</label>
                <div class="col-md-64"><input type="text" id="category" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="describe" class="col-md-36 top-padding">Description:</label>
                <div class="col-md-64"><textarea id="describe" class="form-control" rows="10"></textarea></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">&nbsp;</label>
                <div class="col-md-64 text-center">
                    <input type="button" id="btnUpdateViolationType"
                           class="btn btn-primary" value="Update Violation Type" />
                </div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations Types", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("New Violation Type", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Details on Violation Type", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Remove Violation Type", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </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. Click the ViolationsTypesController.cs tab
  6. To execute, on the main menu, click Debug -> Start Without Debugging
  7. Click the Violation Types link:

    Traffic Tickets System - Violations Types

  8. Click Edit/Update Violation Type:

    Traffic Tickets System - Edit/Update Violation Type

  9. In the Violation Type Id text box, type 3
  10. Click the Find Violation Type button:

    Traffic Tickets System - Edit/Update Violation Type

  11. Change the text of the large text area as follows:

    The vehicle drove through a steady red light. The law in the state requires that when a vehicle approaches a steady red light, it must completely stop and wait for the light to change to green.

    Traffic Tickets System - Edit/Update Violation Type

  12. Click the Update Violation Type button:

    Traffic Tickets System - Edit/Update Violation Type

  13. Click OK on the message box:

    Traffic Tickets System - Violations Types

  14. Return to your programming environment

Deleting a Violation Type

For any reason, an administration may want to stop considering a certain category of violation. To help with this, our application will be equipped with a form that allows a user to delete a violation category.

Practical LearningPractical Learning: Deleting a Violation Type

  1. In the ViolationsTypesController.cs tab, right-click inside the Delete() method and click Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Delete:

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Delete Violation Type";
    }
    
    <h2 class="text-center fw-bold common-font">Delete Violation Type</h2>
    
    <hr />
    
    <form name="frmDeleteViolationType" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="violationTypeId" class="col-md-36 top-padding">Violation Type Id:</label>
                <div class="col-md-32"><input type="text" id="violationTypeId" class="form-control" /></div>
                <div class="col-md-32">
                    <input type="button" id="btnGetViolationType" class="btn btn-primary" value="Get Violation Type" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">Volation Type:</label>
                <div class="col-md-64"><span id="vType"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">Description:</label>
                <div class="col-md-64"><span id="describe"></span></div>
            </div>
        </div>
    
        <hr />
    
        <p class="text-center">
            <input type="button" name="btnDeleteViolationType"
                   class="btn btn-primary" value="Delete Violation Type" />
        </p>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations Types", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("New Violation Type", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Description of a Violation Type", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Violation Type", "Edit", null, htmlAttributes: new { @class = "tts-nav" })
    </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='Delete Violation Type']").on("click", function (event) {
                var car = {
                    ViolationTypeId: $("#violationTypeId").val()
                };
                $.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>
  5. To execute, on the main menu, click Debug -> Start Without Debugging
  6. Click the Violation Types link:

    Traffic Tickets System - Delete Violation

  7. Click the Remove Violation Type link:

    Traffic Tickets System - Edit/Update Violation Type

  8. In the Violation Type Id text box, type 5
  9. Click the Find Violation Type button:

    Traffic Tickets System - Delete Violation Type

  10. Click the Delete Violation Type button:

    Traffic Tickets System - Delete Violation Type

  11. Click OK on the message box:

    Traffic Tickets System - Violations Types

  12. Return to your programming environment

Cameras

A List of Cameras

Some violations are processed by a police officer. Some other violations are proved by a photo or a video taken by some cameras that are installed in some streets and areas of the administration. Our application will allow a user to see a list of cameras that are available and where they are installed.

Practical LearningPractical Learning: Displaying a List of Cameras

  1. In the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...
  2. In the left list of the Add New Scaffolded Item dialog box, click Web API and, in the middle list, click Web API 2 Controller With Actions, Using Entity Framework

    Add New Scaffolded Item

  3. Click Add
  4. In the Model Class combo box, select Camera (TrafficTicketsSystem1.Models)
  5. Make sure the Data Context Class combo box is displaying TicketsManagementModel (TrafficTicketsSystem1.Models).
    Make sure the Controller Name text box is displaying CamerasController:

    Add Controller

    Click Add:
    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 CamerasController : ApiController
        {
            private TicketsManagementModel db = new TicketsManagementModel();
    
            // GET: api/Cameras
            public IQueryable<Camera> GetCameras()
            {
                return db.Cameras;
            }
    
            // 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);
            }
    
            // 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);
            }
    
            // POST: api/Cameras
            [ResponseType(typeof(Camera))]
            public IHttpActionResult PostCamera(Camera camera)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
                db.Cameras.Add(camera);
                db.SaveChanges();
    
                return CreatedAtRoute("DefaultApi", new { id = camera.CameraId }, camera);
            }
    
            // 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);
            }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }
    
            private bool CameraExists(int id)
            {
                return db.Cameras.Count(e => e.CameraId == id) > 0;
            }
        }
    }
  6. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  7. In the middle list of the Add New Scaffolded Item dialog box, click MVC 5 Controller With Read/Write Actions:

    Add New Scaffolded Item

  8. Click Add
  9. Replace Default with Camera to get CameraController

    Add New Scaffolded Item

  10. Click Add
  11. In the Details(), the Edit(), and the Delete() methods, make the id argument nullable:
    using System.Web.Mvc;
    
    namespace TrafficTicketsSystem1.Controllers
    {
        public class CameraController : Controller
        {
            // GET: Camera
            public ActionResult Index()
            {
                return View();
            }
    
            // GET: Camera/Details/5
            public ActionResult Details(int? id)
            {
                return View();
            }
    
            // GET: Camera/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: Camera/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Camera/Edit/5
            public ActionResult Edit(int? id)
            {
                return View();
            }
    
            // POST: Camera/Edit/5
            [HttpPost]
            public ActionResult Edit(int? id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Camera/Delete/5
            public ActionResult Delete(int? id)
            {
                return View();
            }
    
            // POST: Camera/Delete/5
            [HttpPost]
            public ActionResult Delete(int? id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  12. In the CameraController class, right-click Index() and click Add View...
  13. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  14. In the Add View dialog box, make sure the View Name text box is displaying Index

    Add View

    Click Add
  15. Change the webpage as follows:
    @{
        ViewBag.Title = "Traffic Cameras";
    }
    
    <h2 class="text-center fw-bold common-font">Traffic Cameras</h2>
    
    <table class="table table-striped common-font">
        <tr>
            <th class="fw-bold text-center">Camera Id</th>
            <th class="fw-bold">Camera #</th>
            <th class="fw-bold">Make</th>
            <th class="fw-bold">Model</th>
            <th class="fw-bold">Location</th>
        </tr>
    </table>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("New Traffic Camera", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Traffic Camera Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Camera Information", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Remove Traffic Camera", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </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>
  16. Click CameraController.cs tab

Setting Up a Camera

When some type of violation occurs, an installed camera would take a photo or shoot a video. Of course, the camera has to be physically installed on a street. Then, the information about the camera has to be entered into the application. To help with this, we will create a form that can assist a user.

Practical LearningPractical Learning: Setting Up a Camera

  1. In the CameraController class, right-click inside one of the Create() methods -> Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Create

    Add View

    Click Add
  4. Create the form as follows:
    @{
        ViewBag.Title = "Traffic Camera";
    }
    
    <h2 class="text-center fw-bold common-font">New Traffic Camera</h2>
    
    <hr />
    
    <form name="frmCreateTrafficCamera" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="cameraNumber" class="col-md-3 top-padding">Camera #:</label>
                <div class="col-md-9"><input type="text" id="cameraNumber" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="make" class="col-md-3 top-padding">Make:</label>
                <div class="col-md-9"><input type="text" id="make" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="model" class="col-md-3 top-padding">Model:</label>
                <div class="col-md-9"><input type="text" id="model" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="location" class="col-md-3 top-padding">Location:</label>
                <div class="col-md-9"><input type="text" id="location" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-3">&nbsp;</label>
                <div class="col-md-9 text-center">
                    <input type="button" id="btnCreateRecord"
                           class="btn btn-primary" value="Create Traffic Camera" />
                </div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Traffic Cameras", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Traffic Camera Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Camera Information", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Remove Traffic Camera", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </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>
  5. Click the CameraController.cs tab
  6. To execute, on the main menu, click Debug -> Start Without Debugging

    Traffic Tickets System - Home Page

  7. Click the Cameras link:

    Traffic Tickets System - Traffic Cameras

  8. In the webpage, click New Traffic Camera link:

    Traffic Tickets System - New Traffic Camera

  9. Create the following records:

    Traffic Tickets System - Traffic Camera Setup

    Camera # Make Model Location
    DGH-38460 Ashton Digital MPH-6000 Eastern Ave and Asbur Drv
    ELQ-79284 Seaside world BL5 Monroe Str and Westview Rd
    MSR-59575 Ashton Digital MPH-6202 Concordia Blvd and Sunset Way
    29417DHT Wood Sons NG20 Temple Ave and Barclay Rd
    AHR-41518 Igawa Worldwide 442i Eucharist Ave
    WVW-59595 Alley Tech PP-0202 Sunset Street and Warry Street
    987HTR World Ashton 366d Monroe Str at Moon Spr
    485W070 Igawa International 448H Sleepy Hallow Av and Sth Anderson Str

    Traffic Tickets System - Traffic Cameras

  10. Return to your programming environment

Getting the Details of a Camera

Some time to time, a user may want to get the information about a camera. To help the user with this, our application will use a form.

Practical LearningPractical Learning: Getting the Details of a Camera

  1. In the class, right-click Details() -> Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Details

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Traffic Camera Details";
    }
    
    <h2 class="text-center fw-bold common-font">Traffic Camera Details</h2>
    
    <hr />
    
    <form name="frmDetailsTrafficCamera" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="cameraId" class="col-md-36 top-padding">Camera Id:</label>
                <div class="col-md-32"><input type="text" id="cameraId" class="form-control" /></div>
                <div class="col-md-32">
                    <input type="button" id="btnFindRecord" class="btn btn-primary" value="Find Camera" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Camera #:</label>
                <div class="col-md-64"><span id="cameraNumber" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Make:</label>
                <div class="col-md-64"><span id="make" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Model:</label>
                <div class="col-md-64"><span id="model" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row top-padding">
                <label class="col-md-36">Location:</label>
                <div class="col-md-64"><span id="location" class="form-control"></span></div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Traffic Cameras", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("New Traffic Camera", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Camera Information", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Remove Traffic Camera", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </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. Click the CameraController.cs tab
  6. To execute, on the main menu, click Debug -> Start Without Debugging
  7. Click the Cameras link:

    Traffic Tickets System - Traffic Cameras

  8. Click the Traffic Camera Details link:

    Traffic Tickets System - Violations Type Details

  9. In the Camera Id text box, type 4
  10. Click the Find Camera button:

    Traffic Tickets System - Violations Type Details

  11. Return to your programming environment

Updating the Information of a Camera

Some time to time, the information about a camera is changed. To help the user with this, our application will include a webform that allows a user to view and update any detail of an installed camera.

Practical LearningPractical Learning: Updating the Information of a Camera

  1. In the CameraController class, right-click one of the Edit() methods -> Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Edit:

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Edit Camera";
    }
    
    <h2 class="text-center fw-bold common-font">Edit/Update Camera Information</h2>
    
    <hr />
    
    <form name="frmEditTrafficCamera" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="cameraId" class="col-md-36 top-padding">Camera Id:</label>
                <div class="col-md-32"><input type="text" id="cameraId" class="form-control" /></div>
                <div class="col-md-32">
                    <input type="button" id="btnFindRecord" class="btn btn-primary" value="Find Camera" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="cameraNumber" class="col-md-36 top-padding">Camera #:</label>
                <div class="col-md-64"><input type="text" id="cameraNumber" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="make" class="col-md-36 top-padding">Make:</label>
                <div class="col-md-64"><input type="text" id="make" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="model" class="col-md-36 top-padding">Model:</label>
                <div class="col-md-64"><input type="text" id="model" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="location" class="col-md-36 top-padding">Location:</label>
                <div class="col-md-64"><input type="text" id="location" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">&nbsp;</label>
                <div class="col-md-64">
                    <input type="button" id="btnUpdateRecord" class="btn btn-primary" value="Update Camera Details" />
                </div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Traffic Cameras", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("New Traffic Camera", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Traffic Camera Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Remove Traffic Camera", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </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>
  5. Click the CameraController.cs tab
  6. To execute, on the main menu, click Debug -> Start Without Debugging
  7. Click the Cameras link:

    Traffic Tickets System - Traffic Cameras

  8. Click the Edit/Update Camera Information link:

    Traffic Tickets System - Edit/Update Traffic Camera

  9. Change the information of the cameras as follows:

    Traffic Tickets System - Edit/Update Violation Type

    Camera Id Camera # Make Model Location
    1 No change No change No change Eastern Avenue and Ashburry Drive
    2 No change Seaside International BL-5000 Monrovia Street and Westview Road
    4 DHT-29417 Woodson and Sons NG-202 Temple Avenue and Barclay Road
    5 No change No change No change Eucharistus Avenue
    7 HTR-93847 Ashton Digital No change Monrovia Street at Moon Springs
    8 No change No change No change Sleepy Hollow Avenue and South Anderson Street

    Traffic Tickets System - Traffic Cameras

  10. Return to your programming environment

Removing a Camera

If an installed camera becomes useless and/or unnecessary, it must be removed from the system. To assist the user with this, our application will include a form that allows a user to delete an application.

Practical LearningPractical Learning: Removing a Camera

  1. In the CameraController class, right-click one of the Delete() methods and click Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Delete:

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Delete Traffic Camera";
    }
    
    <h2 class="text-center fw-bold common-font">Traffic Camera Removal</h2>
    
    <hr />
    
    <form name="frmDeleteTrafficCamera" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="cameraId" class="col-md-36 top-padding">Camera Id:</label>
                <div class="col-md-32"><input type="text" id="cameraId" class="form-control" /></div>
                <div class="col-md-32">
                    <input type="button" id="btnFindRecord" class="btn btn-primary" value="Find Camera" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Camera #:</label>
                <div class="col-md-64"><span id="cameraNumber" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Make:</label>
                <div class="col-md-64"><span id="make" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Model:</label>
                <div class="col-md-64"><span id="model" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Location:</label>
                <div class="col-md-64"><span id="location" class="form-control"></span></div>
            </div>
        </div>
    
        <hr />
    
        <p class="text-center">
            <input type="button" id="btnDeleteRecord" class="btn btn-primary" value="Remove Traffic Camera" />
        </p>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Traffic Cameras", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("New Traffic Camera", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Traffic Camera Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Camera Information", "Edit", null, htmlAttributes: new { @class = "tts-nav" })
    </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()
                };
                $.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>
  5. To execute, on the main menu, click Debug -> Start Without Debugging
  6. Click the Traffic Cameras link:

    Traffic Tickets System - Traffic Cameras

  7. Click the Remove Traffic Camera link:

    Traffic Tickets System - Traffic Camera Removal

  8. In the Camera Id text box, type 6
  9. Click the Find Camera button:

    Traffic Tickets System - Traffic Camera Removal

  10. Click the Remove Traffic Camera button:

    Traffic Tickets System - Delete Violation Type

  11. Click OK on the message box:

    Traffic Tickets System - Traffic Cameras

  12. Return to your programming environment

Vehicles Drivers

A List of Vehicles Drivers

Infractions are committed by people who drive cars. Normally each driver must possess a driver's license. Those licenses are issued and managed by a state government. For our simple application, we will create the drivers licenses of the drivers of our application.

Practical LearningPractical Learning: Displaying a List of Drivers

  1. In the Solution Explorer, right-click TrafficControllers -> Add -> New Scaffolded Item...
  2. In the middle list of the Add New Scaffolded Item dialog box, make sure Web API 2 Controller With Actions, Using Entity Framework is selected (or click it):

    Add New Scaffolded Item

    Click Add
  3. In the Model Class combo box, select Driver (TrafficTicketsSystem1.Models)
  4. Make sure the Data Context Class combo box is displaying TicketsManagementModel (TrafficTicketsSystem1.Models).
    Make sure the Controller Name text box displays DriversController:

    Add Controller

    Click Add:
    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 DriversController : ApiController
        {
            private TicketsManagementModel db = new TicketsManagementModel();
    
            // GET: api/Drivers
            public IQueryable<Driver> GetDrivers()
            {
                return db.Drivers;
            }
    
            // GET: api/Drivers/5
            [ResponseType(typeof(Driver))]
            public IHttpActionResult GetDriver(int id)
            {
                Driver driver = db.Drivers.Find(id);
                if (driver == null)
                {
                    return NotFound();
                }
    
                return Ok(driver);
            }
    
            // PUT: api/Drivers/5
            [ResponseType(typeof(void))]
            public IHttpActionResult PutDriver(int id, Driver driver)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
                if (id != driver.DriverId)
                {
                    return BadRequest();
                }
    
                db.Entry(driver).State = EntityState.Modified;
    
                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!DriverExists(id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
    
                return StatusCode(HttpStatusCode.NoContent);
            }
    
            // POST: api/Drivers
            [ResponseType(typeof(Driver))]
            public IHttpActionResult PostDriver(Driver driver)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
                db.Drivers.Add(driver);
                db.SaveChanges();
    
                return CreatedAtRoute("DefaultApi", new { id = driver.DriverId }, driver);
            }
    
            // DELETE: api/Drivers/5
            [ResponseType(typeof(Driver))]
            public IHttpActionResult DeleteDriver(int id)
            {
                Driver driver = db.Drivers.Find(id);
                if (driver == null)
                {
                    return NotFound();
                }
    
                db.Drivers.Remove(driver);
                db.SaveChanges();
    
                return Ok(driver);
            }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }
    
            private bool DriverExists(int id)
            {
                return db.Drivers.Count(e => e.DriverId == id) > 0;
            }
        }
    }
  5. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  6. In the middle list of the Add New Scaffolded Item dialog box, click MVC 5 Controller With Read/Write Actions

    Add New Scaffolded Item

  7. Click Add
  8. Replace Default with Driver to get DriverController

    Add Controller

  9. Click Add
  10. In the class, make all id arguments nullable:
    using System.Web.Mvc;
    
    namespace TrafficTicketsSystem1.Controllers
    {
        public class DriverController : Controller
        {
            // GET: Driver
            public ActionResult Index()
            {
                return View();
            }
    
            // GET: Driver/Details/5
            public ActionResult Details(int? id)
            {
                return View();
            }
    
            // GET: Driver/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: Driver/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Driver/Edit/5
            public ActionResult Edit(int? id)
            {
                return View();
            }
    
            // POST: Driver/Edit/5
            [HttpPost]
            public ActionResult Edit(int? id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Driver/Delete/5
            public ActionResult Delete(int? id)
            {
                return View();
            }
    
            // POST: Driver/Delete/5
            [HttpPost]
            public ActionResult Delete(int? id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  11. In the DriverController class, right-click Index() -> Add View...
  12. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  13. In the Add View dialog box, make sure the View Name text box is displaying Index

    Add View

    Click Add
  14. Change the code as follows:
    @{
        ViewBag.Title = "Vehicles Owners/Drivers";
    }
    
    <h2 class="text-center fw-bold common-font">Vehicles Owners/Drivers</h2>
    
    <table class="table table-striped common-font">
        <tr>
            <th class="fw-bold text-center">Driver Id</th>
            <th class="fw-bold">Drv. Lic. #</th>
            <th class="fw-bold">First Name</th>
            <th class="fw-bold">Last Name</th>
            <th class="fw-bold">Address</th>
            <th class="fw-bold">City</th>
            <th class="fw-bold">County</th>
            <th class="fw-bold">State</th>
            <th class="fw-bold">ZIP-Code</th>
        </tr>
    </table>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("New Driver/Owner", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Driver/Owner Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Driver/Owner Information", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Revoke Driver's License", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </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>
  15. Click the DriverController.cs tab

Licensing a Vehicle Driver

A person who drives a car must have a driver's license. To help a user establish such a document, our application will include an appropriate webform. As seen in our database, we will keep the information to a minimum.

Practical LearningPractical Learning: Licensing a Vehicle Driver

  1. In the DriverController class, right-click one of the Create() methods and click Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Create

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Create Driver";
    }
    
    <h2 class="text-center fw-bold common-font">New Vehicle Owner/Driver</h2>
    
    <hr />
    
    <form name="frmCreateVehicleDriver" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="drvLicNbr" class="col-md-36 top-padding">Drv. Lic. #:</label>
                <div class="col-md-64"><input type="text" id="drvLicNbr" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="fName" class="col-md-36 top-padding">First Name:</label>
                <div class="col-md-64"><input type="text" id="fName" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="lName" class="col-md-36 top-padding">Last Name:</label>
                <div class="col-md-64"><input type="text" id="lName" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="adrs" class="col-md-36 top-padding">Address:</label>
                <div class="col-md-64"><input type="text" id="adrs" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="city" class="col-md-36 top-padding">City:</label>
                <div class="col-md-64"><input type="text" id="city" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="county" class="col-md-36 top-padding">County:</label>
                <div class="col-md-64"><input type="text" id="county" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="state" class="col-md-36 top-padding">State:</label>
                <div class="col-md-64"><input type="text" id="state" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="zip" class="col-md-36 top-padding">ZIP Code:</label>
                <div class="col-md-64"><input type="text" id="zip" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding"></label>
                <div class="col-md-64 text-center">
                    <input type="button" id="btnIssueDriversLicense"
                           class="btn btn-primary" value="Issue a Driver's License" />
                </div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Drivers/Owners", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Driver/Owner Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Driver/Owner Information", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Delete Drivers/Owner Record", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </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>
  5. Click the DriverController.cs tab
  6. To execute, on the main menu, click Debug -> Start Without Debugging

    Traffic Tickets System - Home Page

  7. Click the Drivers link:

    Traffic Tickets System - Traffic Cameras

  8. Click the New Driver/Owner link

    Traffic Tickets System - New Vehicle Driver/Owner

  9. In the text boxes, enter the following values and click the Save button after each:

    Traffic Tickets System - New Vehicle Driver/Owner

    Drv. Lic. # First Name Last Name Address City County State ZIP Code
    296 840 681 Simon Havers 1684 Steward Le Kittanning Arms Strongs PA 11563
    273-79-4157 Terrence McConnell 8304 Polland Street Meadowview Washington VA 24361
    A402-630-468 Patrick Atherton 10744 Quincy Blvd Cumberland Allegany MD 21502

    Traffic Tickets System - Traffic Cameras

  10. In the Server Explorer, right-click TrafficTicketsSystem1 and click New Query
  11. In the empty document, type the following code:
    INSERT INTO Drivers(DrvLicNumber, FirstName, LastName, [Address], City, [State], ZIPCode)
    VALUES(N'C-684-394-527', N'Sarah',     N'Cuchran',      N'10804 Euton Road',        N'Shawnee Land',                         N'VA', N'24450');
    GO
    INSERT INTO Drivers(DrvLicNumber, FirstName, LastName, [Address], City, County, [State], ZIPCode)
    VALUES(N'E-928-374-025',  N'Janet',    N'Eubanks',      N'794 Arrow Head Ave',         N'Vyene',        N'Dorchester',     N'MD', N'21669'),
          (N'GV55379422',     N'Frank',    N'Leighton',     N'11428 Swanson Street',       N'Eldorado',     N'Schleicher',     N'TX', N'76932'),
          (N'593-804-597',    N'George',   N'Higgins',      N'884 Willingmont Drive',      N'Krumsville',   N'Berks',          N'PA', N'19530'),
          (N'G483974973',     N'Anthony',  N'Gibbs',        N'672 Pearson Avenue',         N'Springfield',  N'Greene',         N'MO', N'65112'),
          (N'729386468',      N'Victoria', N'Huband',       N'3958 Lubber Court',          N'Middletown',   N'New Castle',     N'DE', N'19709'),
          (N'296806850',      N'Annette',  N'Mann',         N'822 North Freight Avenue',   N'Macon',        N'Noxubee',        N'MS', N'393412'),
          (N'851608526',      N'Patrick',  N'Whalley',      N'10227 Woodrow Rd',           N'Shelleytown',  N'Bedford',        N'TN', N'38561'),
          (N'TM3049805',      N'Denise',   N'Gibson',       N'2794 Bronson Court',         N'Madisonville', N'Madison',        N'TX', N'77862'),
          (N'W639-285-940',   N'David',    N'Woodbank',     N'9703 Abington Ave',          N'Hurlock',      N'Dorchester',     N'MD', N'21643'),
          (N'42803706',       N'James',    N'Rowley',       N'12269 Bingham Street',       N'Briggs Town',  N'Prince Georges', N'MD', N'20776'),
          (N'20374586',       N'Robert',   N'Pearson',      N'648 North Kaduna Boulevard', N'Georgetown',   N'Sussex',         N'DE', N'19942'),
          (N'S-283-942-646',  N'Amil',     N'Saint Burrey', N'4048 Utah Rd',               N'Denville',     N'Morris',         N'NJ', N'07961'),
          (N'KW538479508',    N'Patrick',  N'Fears',        N'10237 Northam Way',          N'Canyon',       N'Randall',        N'TX', N'79015'),
          (N'860-586-175',    N'Kelly',    N'Murray',       N'8622 Rutger Farms Street',   N'Rutger Farms', N'Macon',          N'TN', N'37122');
    GO
  12. To execute, on the SQL Editor toolbar, click the Execute button Execute
  13. Close the Query window
  14. When asked whether you want to save, click No
  15. Return to your programming environment

Getting Information About a Driver

Some time to time, an employee may want to see the details of a driver's license. To help with this, we will add a webform to our application.

Practical LearningPractical Learning: Getting Information About a Vehicle Driver

  1. Click the DriverController.cs tab
  2. In the DriverController class, right-click Details() -> Add View...
  3. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  4. In the Add View dialog box, make sure the View Name text box displays Details

    Add View

    Click Add
  5. Change the webpage as follows:
    @{
        ViewBag.Title = "Driver Details";
    }
    
    <h2 class="text-center fw-bold common-font">Driver/Owner Details</h2>
    
    <hr />
    
    <form name="frmDetailsDriver" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="cameraId" class="col-md-36 top-padding">Driver Id:</label>
                <div class="col-md-32"><input type="text" id="driverId" class="form-control" /></div>
                <div class="col-md-32">
                    <input type="button" id="btnLocateDriver" class="btn btn-primary" value="Locate Driver/Owner" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Drv. Lic. #:</label>
                <div class="col-md-64"><span id="drvLicNbr"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">First Name:</label>
                <div class="col-md-64"><span id="fname"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Last Name:</label>
                <div class="col-md-64"><span id="lname" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Address:</label>
                <div class="col-md-64"><span id="adrs"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">City:</label>
                <div class="col-md-64"><span id="city"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">County:</label>
                <div class="col-md-64"><span id="county"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">State:</label>
                <div class="col-md-64"><span id="state"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">ZIP-Code:</label>
                <div class="col-md-64"><span id="zip"></span></div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Vehicles Drivers/Owners", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("New Driver", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Driver Details", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Revoke Driver's License", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </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>
  6. Click the DriverController.cs tab
  7. To execute, on the main menu, click Debug -> Start Without Debugging
  8. Click the Drivers link:

    Traffic Tickets System - Traffic Cameras

  9. Click the Driver/Owner Details link:

    Traffic Tickets System - Violations Type Details

  10. In the Driver Id text box, type 3
  11. Click the Locate Driver/Owner button:

    Traffic Tickets System - Violations Type Details

  12. Return to your programming environment

Updating the Details of a Driver

A piece of information about a driver can change. When that happens, the database must be updated. We will make this happen in our application through an appropriate form.

Practical LearningPractical Learning: Updating the Information of a Camera

  1. In the DriverController class, right-click one of the Edit() methods -> Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Edit:

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Edit Driver";
    }
    
    <h2 class="text-center fw-bold common-font">Edit/Update Driver Information</h2>
    
    <hr />
    
    <form name="frmEditDriver" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="chauffeur" class="col-md-36 top-padding">Driver Id:</label>
                <div class="col-md-32"><input type="text" id="chauffeur" class="form-control" /></div>
                <div class="col-md-32">
                    <input type="button" id="btnGetDriver" class="btn btn-primary" value="Find Driver" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="drvLicNbr" class="col-md-36 top-padding">Drv. Lic. #:</label>
                <div class="col-md-64"><input type="text" id="drvLicNbr" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="fName" class="col-md-36 top-padding">First Name:</label>
                <div class="col-md-64"><input type="text" id="fName" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="lName" class="col-md-36 top-padding">Last Name:</label>
                <div class="col-md-64"><input type="text" id="lName" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="adrs" class="col-md-36 top-padding">Address:</label>
                <div class="col-md-64"><input type="text" id="adrs" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="city" class="col-md-36 top-padding">City:</label>
                <div class="col-md-64"><input type="text" id="city" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="county" class="col-md-36 top-padding">County:</label>
                <div class="col-md-64"><input type="text" id="county" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="state" class="col-md-36 top-padding">State:</label>
                <div class="col-md-64"><input type="text" id="state" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="zip" class="col-md-36 top-padding">ZIP-Code:</label>
                <div class="col-md-64"><input type="text" id="zip" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">&nbsp;</label>
                <div class="col-md-64 text-center">
                    <input type="button" id="btnUpdateRecord"
                           class="btn btn-primary" value="Update Camera Details" />
                </div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Drivers/Owners", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("New Driver", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Driver/Owner Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Delete Drivers/Owner Record", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </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 now up-to-date.")
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>
  5. Click the DriverController.cs tab
  6. To execute, on the main menu, click Debug -> Start Without Debugging
  7. Click the Drivers link:

    Traffic Tickets System - Traffic Cameras

  8. Click the Edit/Update Driver Information link:

    Traffic Tickets System - Edit/Update Traffic Camera

  9. Change the information of the Drivers as follows:
    Driver Id Drv. Lic. # First Name Last Name Address City County State ZIP Code
    1 296-840-681 No change No change No change 1884 Stewart Lane Armstrong No change 15638
    5 No change Jeannette No change 7294 Arrowhead Avenue Vienna No change No change 21869
    16 No change Emilie Sainsbury No change Shelbyville No change No change No change

    Traffic Tickets System - Edit/Update Violation Type

    Traffic Tickets System - Traffic Cameras

  10. Return to your programming environment

Removing a Driver

For any reason, an administration may want to remove a driver's license from a system. To let the user perform this operation, we will create a webform in our application.

Practical LearningPractical Learning: Removing a Camera

  1. In the DriverController class, right-click one of the Delete() methods and click Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Delete:

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Delete Driver";
    }
    
    <h2 class="text-center fw-bold common-font">Delete Driver's Record</h2>
    
    <hr />
    
    <form name="frmDeleteDrivers" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="driverId" class="col-md-36 top-padding">Driver Id:</label>
                <div class="col-md-32"><input type="text" id="driverId" class="form-control small" /></div>
                <div class="col-md-32">
                    <input type="button" name="btnFindDriver" class="btn btn-primary" value="Find Driver's Record" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Drv. Lic. #:</label>
                <div class="col-md-64"><span id="dln" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">First Name:</label>
                <div class="col-md-64"><span id="fname" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Last Name:</label>
                <div class="col-md-64"><span id="lname" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Address:</label>
                <div class="col-md-64"><span name="adrs" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">City:</label>
                <div class="col-md-64"><span name="city" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">County:</label>
                <div class="col-md-64"><span name="county" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">State:</label>
                <div class="col-md-64"><span name="state" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">ZIP-Code:</label>
                <div class="col-md-64"><span name="zip" class="form-control"></span></div>
            </div>
        </div>
    
        <hr />
    
        <p class="text-center">
            <input type="button" id="btnDeleteRegistration" name="btnRevokeRegistration"
                   class="btn btn-primary" value="Delete Driver Record" />
        </p>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Drivers/Owners", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Create Drivers/Owner Record", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Driver/Owner Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Driver/Owner Information", "Edit", null, htmlAttributes: new { @class = "tts-nav" })
    </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[class='form-control small']").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='Delete Driver Record']").on("click", function (event) {
                var driver = {
                    DriverId:     $("input[class='form-control small']").val()
                };
                
                $.ajax({
                    data:         driver,
                    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>
  5. Click the DriverController.cs tab
  6. To execute, on the main menu, click Debug -> Start Without Debugging
  7. Click the Drivers link:

    Traffic Tickets System - Vehicles Drivers

  8. Click the Revoke Drivers's Livense link:

    Traffic Tickets System - Delete Vehicle Driver Record

  9. In the Driver Id text box, type 14
  10. Click the Find Driver's Record button:

    Traffic Tickets System - Delete Vehicle Driver Record

  11. Click the Revoke Drivers's License button
  12. Click OK on the message box:

    Traffic Tickets System - Vehicles Drivers

  13. Return to your programming environment

Vehicles

Introduction

Vehicles records are created and managed by a state government. For our simple application, we will register the cars in our system. Before doing that, we will make sure a user has the ability to display a list of vehicles.

Practical LearningPractical Learning: Displaying a List of Vehicles

  1. In the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...
  2. In the middle list of the Add New Scaffolded Item dialog box, under Common, click Web API and, in the middle list, click Web API 2 Controller With Actions, Using Entity Framework:

    Add New Scaffolded Item

  3. Click Add
  4. In the Model Class combo box, select Vehicle (TrafficTicketsSystem1.Models)
  5. Make sure the Data Context Class combo box is displayinig TicketsManagementModel (TrafficTicketsSystem1.Models).
    Make sure the Controller Name is displaying VehiclesController:

    Add Controller

    Click Add:
    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 VehiclesController : ApiController
        {
            private TicketsManagementModel db = new TicketsManagementModel();
    
            // GET: api/Vehicles
            public IQueryable<Vehicle> GetVehicles()
            {
                return db.Vehicles;
            }
    
            // GET: api/Vehicles/5
            [ResponseType(typeof(Vehicle))]
            public IHttpActionResult GetVehicle(int id)
            {
                Vehicle vehicle = db.Vehicles.Find(id);
                if (vehicle == null)
                {
                    return NotFound();
                }
    
                return Ok(vehicle);
            }
    
            // PUT: api/Vehicles/5
            [ResponseType(typeof(void))]
            public IHttpActionResult PutVehicle(int id, Vehicle vehicle)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
                if (id != vehicle.VehicleId)
                {
                    return BadRequest();
                }
    
                db.Entry(vehicle).State = EntityState.Modified;
    
                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!VehicleExists(id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
    
                return StatusCode(HttpStatusCode.NoContent);
            }
    
            // POST: api/Vehicles
            [ResponseType(typeof(Vehicle))]
            public IHttpActionResult PostVehicle(Vehicle vehicle)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
                db.Vehicles.Add(vehicle);
                db.SaveChanges();
    
                return CreatedAtRoute("DefaultApi", new { id = vehicle.VehicleId }, vehicle);
            }
    
            // DELETE: api/Vehicles/5
            [ResponseType(typeof(Vehicle))]
            public IHttpActionResult DeleteVehicle(int id)
            {
                Vehicle vehicle = db.Vehicles.Find(id);
                if (vehicle == null)
                {
                    return NotFound();
                }
    
                db.Vehicles.Remove(vehicle);
                db.SaveChanges();
    
                return Ok(vehicle);
            }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }
    
            private bool VehicleExists(int id)
            {
                return db.Vehicles.Count(e => e.VehicleId == id) > 0;
            }
        }
    }
  6. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  7. In the left list of the Add New Scaffolded Item dialog box, click MVC and, in the middle list, click MVC 5 Controller With Read/Write Actions

    Add New Scaffolded Item

  8. Click Add
  9. Replace Default with Vehicle to get VehicleController
  10. Click Add
  11. In the VehicleController class, make all id arguments nullable:
    using System.Web.Mvc;
    
    namespace TrafficTicketsSystem1.Controllers
    {
        public class VehicleController : Controller
        {
            // GET: Vehicle
            public ActionResult Index()
            {
                return View();
            }
    
            // GET: Vehicle/Details/5
            public ActionResult Details(int? id)
            {
                return View();
            }
    
            // GET: Vehicle/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: Vehicle/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Vehicle/Edit/5
            public ActionResult Edit(int? id)
            {
                return View();
            }
    
            // POST: Vehicle/Edit/5
            [HttpPost]
            public ActionResult Edit(int? id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: Vehicle/Delete/5
            public ActionResult Delete(int? id)
            {
                return View();
            }
    
            // POST: Vehicle/Delete/5
            [HttpPost]
            public ActionResult Delete(int? id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
        }
    }
  12. In the class, right-click Index() -> Add View...
  13. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  14. In the Add View dialog box, make sure the View Name text box is displaying Index

    Add View

    Click Add
  15. Change the document as follows:
    @{
        ViewBag.Title = "Vehicles";
    }
    
    <h2 class="text-center fw-bold common-font">Vehicles Registrations</h2>
    
    <table class="table table-striped common-font">
        <tr>
            <th class="fw-bold text-center">Vehicle Id</th>
            <th class="fw-bold">Tag #</th>
            <th class="fw-bold">Drv. Lic. #</th>
            <th class="fw-bold">Make</th>
            <th class="fw-bold">Model</th>
            <th class="fw-bold">Year</th>
            <th class="fw-bold">Color</th>
        </tr>
    </table>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("New Vehicle Registration", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Vehicle Registration Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Vehicle Registration Details", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Delete Vehicle Registration", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </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>
  16. Click the VehicleController.cs tab

Registering a Vehicle

Before a vehicle is allowed to circulate in the street, a record must be created in the administration's system. Our application will have a webform that can be used to register a vehicle. As seen in our database, we will keep the information to a minimum.

Practical LearningPractical Learning: Registering a Vehicle

  1. In the VehicleController class, right-click one of the Create() methods and click Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Create

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Vehicle Registration";
    }
    
    <h2 class="text-center fw-bold common-font">New Vehicle Registration</h2>
    
    <hr />
    
    <form name="VehicleRegistration" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="tagNbr" class="col-md-36 top-padding">Vehicle Tag #:</label>
                <div class="col-md-64"><input type="text" id="tagNbr" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="drvLicNbr" class="col-md-36 top-padding">Drv. Lic. #:</label>
                <div class="col-md-64"><input type="text" id="drvLicNbr" class="form-control" /></div>
            </div>
            <div class="form-group row">
                <label for="ownerName" class="col-md-36 top-padding">Owner/Driver:</label>
                <div class="col-md-64">
                    <span id="ownerName" name="ownerName"></span>
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-36"></label>
                <div class="col-md-64">
                    <span id="ownerAddress" name="ownerAddress"></span>
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-36"></label>
                <div class="col-md-64">
                    <span id="ownerCityState" name="ownerCityState"></span>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="make" class="col-md-36 top-padding">Make:</label>
                <div class="col-md-64"><input type="text" id="make" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="model" class="col-md-36 top-padding">Model:</label>
                <div class="col-md-64"><input type="text" id="model" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="year" class="col-md-36 top-padding">Year:</label>
                <div class="col-md-64"><input type="text" id="year" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="clr" class="col-md-36 top-padding">Color:</label>
                <div class="col-md-64"><input type="text" id="clr" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">&nbsp;</label>
                <div class="col-md-64 text-center">
                    <input type="button" id="btnRegisterVehicle"
                           class="btn btn-primary" value="Save this Vehicle Registration" />
                </div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Vehicles Registrations", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Vehicle Registration Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Vehicle Registration", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Delete Vehicle Registration", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </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()) {
                                $("span[name='ownerName']").text(person["FirstName"] + " " + person["LastName"]);
                                $("span[name='ownerAddress']").text(person["Address"]);
                                $("span[name='ownerCityState']").text(person["City"] + ", " +
                                    person["State"] + " " +
                                    person["ZIPCode"]);
                            }
                        });
                    }
                });
            }); // 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. Click the VehicleController.cs tab
  6. To execute, on the main menu, click Debug -> Start Without Debugging

    Traffic Tickets System - Home Page

  7. Click the Vehicles link:

    Traffic Tickets System - Vehicles Registrations

  8. Click the New Vehicle Registration link

    Traffic Tickets System - New Vehicle Registration

  9. In the text boxes, enter the following values and click the Save button after each:

    Traffic Tickets System - New Vehicle Registration

    Traffic Tickets System - New Vehicle Registration

    Tag # Drv. Lic. # Make Model Year Color
    8DE9275 296-840-681 Ford Escape ST 2023 Vapor Blue
    KLT4805 593-804-597 Toyota Corolla LE 2021 Maroon

    Traffic Tickets System - Vehicles Registrations

  10. In the Server Explorer, right-click TrafficTicketsSystem1 and click New Query
  11. In the empty document, type the following code:
    INSERT INTO Vehicles(TagNumber, DrvLicNumber, Make, Model, VehicleYear, Color)
    VALUES(N'807-394', N'851-608-526',   N'Toyota',   N'Camry',      N'2010', N'Silver'),
    	  (N'KAS9314', N'W639-285-940',  N'Cadillac', N'Escalade',   N'2018', N'Cream'),
    	  (N'FKEWKR',  N'72938468',      N'Toyota',   N'Camry',      N'2020', N'Silver'),
    	  (N'HAK3936', N'S-283-942-646', N'Chrysler', N'Crossfire',  N'2020', N'Red'),
    	  (N'PER2849', N'296-840-681',   N'Buick',    N'LeSabre',    N'2022', N'Silver'),
    	  (N'379-708', N'593-804-597',   N'Toyota',   N'Prius',      N'2025', N'Gray'),
    	  (N'938-074', N'A-402-630-468', N'Ford',     N'Bronco',     N'2025', N'Green'),
    	  (N'MWH4685', N'851-608-526',   N'Honda',    N'Accord',     N'2019', N'Blue'),
    	  (N'971384',  N'E-928-374-025', N'BMW',      N'325i',       N'2015', N'Navy'),
    	  (N'380-740', N'729-386-468',   N'Chrysler', N'Pacifica',   N'2022', N'White'),
    	  (N'KD5842',  N'860596175',     N'Nissan',   N'Rogue',      N'2020', N'Yellow'),
    	  (N'5293WPL', N'C-684-394-527', N'Ford',     N'F-150',      N'2018', N'Light Gray'),
    	  (N'394-849', N'593-804-597',   N'Toyota',   N'Corolla',    N'2015', N'Red'),
    	  (N'PP-9584', N'851-608-526',   N'Mazda',    N'CX-30',      N'2024', N'Dark Red'),
    	  (N'MKR9374', N'273-79-4157',   N'Lincoln',  N'MKT',        N'2018', N'Black'),
    	  (N'2937DG',  N'860596175',     N'Ford',     N'Mustang GT', N'2025', N'Blue Metallic');
    GO
  12. To execute, on the SQL Editor toolbar, click the Execute button Execute
  13. Close the Query window
  14. When asked whether you want to save, click No
  15. Click the VehicleController.cs tab

Viewing the Details of a Vehicle

Some time to time, an employee may want to see the information related to a vehicle. To assist the user with this operation, we will create a certain webpage in our application.

Practical LearningPractical Learning: Viewing the Details of a Vehicle

  1. In the VehicleController class, right-click inside the Details() method and click Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Details

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Vehicle Details";
    }
    
    <h2 class="text-center fw-bold common-font">Vehicle Details</h2>
    
    <hr />
    
    <form name="frmDetailsVehicle" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="cameraId" class="col-md-36 top-padding">Vehicle Id:</label>
                <div class="col-md-32"><input type="text" id="carId" class="form-control small" /></div>
                <div class="col-md-32">
                    <input type="button" id="btnFindVehicle" class="btn btn-primary" value="Find Vehicle" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Tag #:</label>
                <div class="col-md-64"><span class="tagNbr form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Drv. Lic. #:</label>
                <div class="col-md-64"><span class="dln form-control"></span></div>
            </div>
    
            <input type="hidden" id="btnLocateDriver" value="Find Driver" />
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">Owner/Driver:</label>
                <div class="col-md-64">
                    <span id="ownerName" name="ownerName"></span>
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-36"></label>
                <div class="col-md-64">
                    <span id="ownerAddress" name="ownerAddress"></span>
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-36"></label>
                <div class="col-md-64">
                    <span id="ownerCityState" name="ownerCityState"></span>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Make:</label>
                <div class="col-md-64"><span class="make form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Model:</label>
                <div class="col-md-64"><span class="mdl form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Year:</label>
                <div class="col-md-64"><span class="year form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Color:</label>
                <div class="col-md-64"><span class="color form-control"></span></div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Vehicles", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Vehicle Registration", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Vehicle", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Delete Vehicle Record", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $(".btn-primary").on("click", function (event) {
                var drvLicNbr = "";
    
                $.ajax({
                    method: "GET",
                    dataType: "json",
                    url: "/api/Vehicles/" + $(".small").val(),
                    success: function (data) {
                        $("span.tagNbr").text(data.TagNumber);
                        $("span.dln").text(data.DrvLicNumber);
                        drvLicNbr = data.DrvLicNumber;
                        $("span.make").text(data.Make);
                        $("span.mdl").text(data.Model);
                        $("span.year").text(data.VehicleYear);
                        $("span.color").text(data.Color);
    
                        $("span[name='ownerName']").text("");
                        $("span[name='ownerAddress']").text("");
                        $("span[name='ownerCityState']").text("");
    
                        locateDriver();
                    }
                });
    
                $("#btnLocateDriver").on("click", function (event) {
                    locateDriver();
                });
    
                function locateDriver() {
                    $.ajax({
                        method: "GET",
                        dataType: "json",
                        url: "/api/Drivers/" + $("span.dln").val(),
                        success: function (data) {
                            $.each(data, function (index, person) {
                                if (person["DrvLicNumber"] === drvLicNbr) {
                                    $("span[name='ownerName']").text(person["FirstName"] + " " +
                                        person["LastName"]);
                                    $("span[name='ownerAddress']").text(person["Address"]);
                                    $("span[name='ownerCityState']").text(person["City"] + ", " +
                                        person["State"] + " " +
                                        person["ZIPCode"]);
                                }
                            });
    
                        }
                    });
                }
            });
        });
    </script>
  5. Click the VehicleController.cs tab
  6. To execute, on the main menu, click Debug -> Start Without Debugging
  7. Click the Vehicles link:

    Traffic Tickets System - Vehicles Registrations

  8. Click the Vehicle Details link:

    Traffic Tickets System - Vehicle Details

  9. In the Vehicle Id text box, type 3
  10. Click the Find Vehicle button:

    Traffic Tickets System - Violations Type Details

  11. Return to your programming environment

Updating the Information of a Vehicle

Many times throughout the lifetime of a vehicle, its information changes from time to time. Of course, such information must be changed in an administration's system. To make this happen, our application will have an appropriate webform.

Practical LearningPractical Learning: Updating the Information of a Vehicle

  1. In the VehicleController class, right-click one of the Edit() methods -> Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Edit:

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Edit Vehicle";
    }
    
    <h2 class="text-center fw-bold common-font">Edit/Update Vehicle Information</h2>
    
    <hr />
    
    <form name="frmEditVehicle" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="carId" class="col-md-36 top-padding">Vehicle Id:</label>
                <div class="col-md-32"><input type="text" id="carId" name="carId" class="form-control" /></div>
                <div class="col-md-32">
                    <input type="button" id="btnLocateVehicle" class="btn btn-primary" value="Find Vehicle" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="drvLicNbr" class="col-md-36 top-padding">Drv. Lic. #:</label>
                <div class="col-md-64">
                    <input type="text" id="drvLicNbr" name="drvLicNbr" class="form-control" />
                </div>
            </div>
    
            <input type="hidden" id="btnLocateDriver" class="btn btn-primary" value="Find Driver" />
    
            <div class="form-group row">
                <label class="col-md-36">Owner/Driver:</label>
                <div class="col-md-64">
                    <span id="ownerName" name="ownerName"></span>
                </div>
            </div>
    
            <div class="form-group row">
                <label class="col-md-36"></label>
                <div class="col-md-64">
                    <span id="ownerAddress" name="ownerAddress"></span>
                </div>
            </div>
    
            <div class="form-group row">
                <label class="col-md-36"></label>
                <div class="col-md-64">
                    <span id="ownerCityState" name="ownerCityState"></span>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="tagNbr" class="col-md-36 top-padding">Vehicle Tag #:</label>
                <div class="col-md-64"><input type="text" id="tagNbr" name="tagNbr" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="make" class="col-md-36 top-padding">Make:</label>
                <div class="col-md-64"><input type="text" id="make" name="make" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="model" class="col-md-36 top-padding">Model:</label>
                <div class="col-md-64"><input type="text" id="model" name="model" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="year" class="col-md-36 top-padding">Year:</label>
                <div class="col-md-64"><input type="text" id="year" name="year" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="color" class="col-md-36 top-padding">Color:</label>
                <div class="col-md-64"><input type="text" id="color" name="color" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">&nbsp;</label>
                <div class="col-md-64">
                    <input type="button" id="btnUpdateVehicleRegistration"
                           class="btn btn-primary" value="Update Vehicle Registration" />
                </div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Vehicles Registrations", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Create Vehicle Registration", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Vehicle Registration Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Delete Vehicle Registration", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnLocateVehicle").click(function (event) {
                var drvLicNbr = "";
    
                $.ajax({
                    method: "GET",
                    dataType: "json",
                    url: "/api/Vehicles/" + $("input[name='carId']").val(),
                    success: function (data) {
                        $("input[name='tagNbr']").val(data.TagNumber);
                        $("input[name='drvLicNbr']").val(data.DrvLicNumber);
                        drvLicNbr = data.DrvLicNumber;
                        $("input[name='make']").val(data.Make);
                        $("input[name='model']").val(data.Model);
                        $("input[name='year']").val(data.VehicleYear);
                        $("input[name='color']").val(data.Color);
    
                        locateDriver();
                    }
                });
    
                $("#btnLocateDriver").on("click", function (event) {
                    locateDriver();
                });
    
                function locateDriver() {
                    $.ajax({
                        method: "GET",
                        dataType: "json",
                        url: "/api/Drivers/",
                        success: function (data) {
                            $.each(data, function (index, person) {
                                if (person["DrvLicNumber"] === $("input[name='drvLicNbr']").val()) {
                                    $("span[name='ownerName']").text(person["FirstName"] + " " +
                                                                     person["LastName"]);
                                    $("span[name='ownerAddress']").text(person["Address"]);
                                    $("span[name='ownerCityState']").text(person["City"] + ", " +
                                                                          person["State"] + " " +
                                                                          person["ZIPCode"]);
                                }
                            });
                        }
                    });
                }
            });
    
            $("input[name='drvLicNbr']").blur(function (event) {
                //alert("The Driver's License text box lost focus.");
                $.ajax({
                    method: "GET",
                    dataType: "json",
                    url: "/api/Drivers/",
                    success: function (data) {
                        $.each(data, function (index, person) {
                            if (person["DrvLicNumber"] === $("input[name='drvLicNbr']").val()) {
                                $("span[name='ownerName']").text(person["FirstName"] + " " +
                                    person["LastName"]);
                                $("span[name='ownerAddress']").text(person["Address"]);
                                $("span[name='ownerCityState']").text(person["City"] + ", " +
                                    person["State"] + " " +
                                    person["ZIPCode"]);
                            }
                        });
                    }
                });
            }); // Driver's License Number Lost Focus
    
            $("#btnUpdateVehicleRegistration").click(function (event) {
                var car = {
                    VehicleId:    $("input[name='carId']").val(),
                    TagNumber:    $("input[name='tagNbr']").val(),
                    DrvLicNumber: $("input[name='drvLicNbr']").val(),
                    Make:         $("input[name='make']").val(),
                    Model:        $("input[name='model']").val(),
                    VehicleYear:  $("input[name='year']").val(),
                    Color:        $("input[name='color']").val()
                };
                $.ajax({
                    data: car,
                    method:       "PUT",
                    url:          "/api/Vehicles/" + $("input[name='carId").val(),
                    success: function (data) {
                        alert("The information about the vehicle has been updated.")
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>
  5. Click the VehicleController.cs tab
  6. To execute, on the main menu, click Debug -> Start Without Debugging
  7. Click the Vehicles link:

    Traffic Tickets System - Traffic Cameras

  8. Click the Edit/Update Vehicle Information link:

    Traffic Tickets System - Edit/Update Vehicle Registration

  9. In the Vehicle Id text box, type 9
  10. Click the Find Vehicle button:

    Traffic Tickets System - Violations Type Details

  11. In the Vehicle Id text box, change the value to 5
  12. Click the Find Vehicle button:

    Traffic Tickets System - Violations Type Details

  13. Change the information of some of the Vehicles as follows:
    Vehicle Id Tag # Drv. Lic. # Make Model Year Color
    5 973FKE 20374586 No change No change 2010 Black
    8 No change 296-840-681 No change Highlander XLE 2024 Celestial Silver
    13 No change No change No change Pathfinder 2025 Green Pearl / Super Black

    Traffic Tickets System - Edit/Update Violation Type

    Traffic Tickets System - Traffic Cameras

  14. Return to your programming environment

Removing a Vehicle

When the record of a vehicle is not necessary, it must be deleted from a system. In our application, we will create a webform that can be used to remove the record of a vehicle.

Practical LearningPractical Learning: Removing a Camera

  1. In the VehicleController class, right-click one of the Delete() methods and click Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Delete:

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Delete Vehicle";
    }
    
    <h2 class="text-center fw-bold common-font">Delete Vehicle Registration</h2>
    
    <hr />
    
    <form name="frmDeleteVehicles" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="carId" class="col-md-36 top-padding">Vehicle Id:</label>
                <div class="col-md-32"><input type="text" name="carId" class="form-control" /></div>
                <div class="col-md-32">
                    <input type="button" name="btnFindVehicleRegistration"
                           class="btn btn-primary" value="Find Vehicle" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Vehicle Tag #:</label>
                <div class="col-md-64"><span name="tagNbr" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Owner Drv. Lic. #:</label>
                <div class="col-md-64"><span name="dln" class="form-control"></span></div>
            </div>
    
            <input type="hidden" id="btnLocateDriver" class="btn btn-primary" value="Find Driver" />
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">Owner/Driver:</label>
                <div class="col-md-64">
                    <span id="ownerName" name="ownerName"></span>
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-36"></label>
                <div class="col-md-64">
                    <span id="ownerAddress" name="ownerAddress"></span>
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-36"></label>
                <div class="col-md-64">
                    <span id="ownerCityState" name="ownerCityState"></span>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Make:</label>
                <div class="col-md-64"><span name="manufacturer" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Model:</label>
                <div class="col-md-64"><span name="model" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Year:</label>
                <div class="col-md-64"><span name="yr" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Color:</label>
                <div class="col-md-64"><span name="color" class="form-control"></span></div>
            </div>
        </div>
    
        <hr />
    
        <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", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Create Vehicle Registration", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Vehicle Registration Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Vehicle Registration", "Edit", null, htmlAttributes: new { @class = "tts-nav" })
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("input[value='Find Vehicle']").on("click", function (event) {
                var drvLicNbr = "";
    
                $.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);
                        drvLicNbr = 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);
    
                        $("span[name='ownerName']").text("");
                        $("span[name='ownerAddress']").text("");
                        $("span[name='ownerCityState']").text("");
    
                        locateDriver();
                    } // success
                }); // $.ajax
    
                $("#btnLocateDriver").on("click", function (event) {
                    locateDriver();
                });
    
                function locateDriver() {
                    $.ajax({
                        method: "GET",
                        dataType: "json",
                        url: "/api/Drivers/" + $("span[name='dln']").val(),
                        success: function (data) {
                            $.each(data, function (index, person) {
                                if (person["DrvLicNumber"] === drvLicNbr) {
                                    $("span[name='ownerName']").text(person["FirstName"] + " " +
                                        person["LastName"]);
                                    $("span[name='ownerAddress']").text(person["Address"]);
                                    $("span[name='ownerCityState']").text(person["City"] + ", " +
                                        person["State"] + " " +
                                        person["ZIPCode"]);
                                }
                            });
    
                        }
                    });
                }
            });
    
            $("input[value='Revoke Vehicle Registration']").on("click", function (event) {
                var car = {
                    VehicleId:    $("input[name='carId']").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. Click the VehicleController.cs tab
  6. To execute, on the main menu, click Debug -> Start Without Debugging
  7. Click the Vehicles link:

    Traffic Tickets System - Traffic Cameras

  8. Click the Remove Vehicle link:

    Traffic Tickets System - Traffic Camera Removal

  9. In the Vehicle Id text box, type 12
  10. Click the Locate Vehicle button:

    Traffic Tickets System - Traffic Camera Removal

  11. Click the Delete Vehicle Registration button:

    Traffic Tickets System - Delete Violation Type

  12. Click OK on the message box:

    Traffic Tickets System - Traffic Cameras

  13. Return to your programming environment

Traffic Violations

Introduction

An administration keeps a list of traffic violations. In our application, we will create a webpage that allows a user to see such a list.

Practical LearningPractical Learning: Showing Traffic Violations

  1. In the Solution Explorer, right-click Controllers -> Add -> Controller...
  2. In the left list of the Add New Scaffolded Item dialig box, click Web API
  3. In the middle list, click Web API 2 Controller With Actions, Using Entity Framework:

    Add New Scaffolded Item

  4. Click Add
  5. In the Model Class combo box, select TrafficViolation (TrafficTicketsSystem1.Models)
  6. Make sure the Data Context Class is displaying TicketsManagementModel (TrafficTicketsSystem1.Models).
    Make sure the Controller Name is displaying TrafficViolationsController:

    Add Controller

    Click Add:
    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 TrafficViolationsController : ApiController
        {
            private TicketsManagementModel db = new TicketsManagementModel();
    
            // GET: api/TrafficViolations
            public IQueryable<TrafficViolation> GetTrafficViolations()
            {
                return db.TrafficViolations;
            }
    
            // GET: api/TrafficViolations/5
            [ResponseType(typeof(TrafficViolation))]
            public IHttpActionResult GetTrafficViolation(int id)
            {
                TrafficViolation trafficViolation = db.TrafficViolations.Find(id);
                if (trafficViolation == null)
                {
                    return NotFound();
                }
    
                return Ok(trafficViolation);
            }
    
            // PUT: api/TrafficViolations/5
            [ResponseType(typeof(void))]
            public IHttpActionResult PutTrafficViolation(int id, TrafficViolation trafficViolation)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
                if (id != trafficViolation.TrafficViolationId)
                {
                    return BadRequest();
                }
    
                db.Entry(trafficViolation).State = EntityState.Modified;
    
                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TrafficViolationExists(id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
    
                return StatusCode(HttpStatusCode.NoContent);
            }
    
            // POST: api/TrafficViolations
            [ResponseType(typeof(TrafficViolation))]
            public IHttpActionResult PostTrafficViolation(TrafficViolation trafficViolation)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
                db.TrafficViolations.Add(trafficViolation);
                db.SaveChanges();
    
                return CreatedAtRoute("DefaultApi", new { id = trafficViolation.TrafficViolationId }, trafficViolation);
            }
    
            // DELETE: api/TrafficViolations/5
            [ResponseType(typeof(TrafficViolation))]
            public IHttpActionResult DeleteTrafficViolation(int id)
            {
                TrafficViolation trafficViolation = db.TrafficViolations.Find(id);
                if (trafficViolation == null)
                {
                    return NotFound();
                }
    
                db.TrafficViolations.Remove(trafficViolation);
                db.SaveChanges();
    
                return Ok(trafficViolation);
            }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }
    
            private bool TrafficViolationExists(int id)
            {
                return db.TrafficViolations.Count(e => e.TrafficViolationId == id) > 0;
            }
        }
    }
  7. In the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...
  8. In the left list of the Add New Scaffolded Item dialog box, click MVC and, in the middle list, click MVC 5 Controller With Read/Write Actions:

    Add New Scaffolded Item

  9. Click Add
  10. Replace Default with TrafficViolation to get TrafficViolationController

    Add Controller

  11. click Add
  12. Change the TrafficViolationController class as follows:
    using System.Web.Mvc;
    
    namespace TrafficTicketsSystem1.Controllers
    {
        public class TrafficViolationController : Controller
        {
            // GET: TrafficViolation
            public ActionResult Index()
            {
                return View();
            }
    
            // GET: TrafficViolation/Details/5
            public ActionResult Details(int? id)
            {
                return View();
            }
    
            // GET: TrafficViolation/Create
            public ActionResult Create()
            {
                return View();
            }
    
            // POST: TrafficViolation/Create
            [HttpPost]
            public ActionResult Create(FormCollection collection)
            {
                try
                {
                    // TODO: Add insert logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: TrafficViolation/Edit/5
            public ActionResult Edit(int? id)
            {
                return View();
            }
    
            // POST: TrafficViolation/Edit/5
            [HttpPost]
            public ActionResult Edit(int? id, FormCollection collection)
            {
                try
                {
                    // TODO: Add update logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: TrafficViolation/Delete/5
            public ActionResult Delete(int? id)
            {
                return View();
            }
    
            // POST: TrafficViolation/Delete/5
            [HttpPost]
            public ActionResult Delete(int? id, FormCollection collection)
            {
                try
                {
                    // TODO: Add delete logic here
    
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
    
            // GET: TrafficViolation/CitationMessage/5
            public ActionResult CitationMessage(int? id)
            {
                return View();
            }
        }
    }
  13. In the class, right-click Index() -> Add View...
  14. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  15. In the Add View dialog box, make sure the View Name text box is displaying Index

    Add View

    Click Add
  16. Create the webpage as follows:
    @{
        ViewBag.Title = "Traffic Violations";
    }
    
    <h2 class="text-center fw-bold common-font">Traffic Violations</h2>
    
    <table class="table table-striped common-font">
        <tr>
            <th class="fw-bold text-center">Violation Id</th>
            <th class="fw-bold text-center">Traffic Violation #</th>
            <th class="fw-bold text-center">Camera #</th>
            <th class="fw-bold text-center">Tag #</th>
            <th class="fw-bold">Violation</th>
            <th class="fw-bold text-center">Date</th>
            <th class="fw-bold text-center">Time</th>
            <th class="fw-bold text-center">Photo Available</th>
            <th class="fw-bold text-center">Video Available</th>
            <th class="fw-bold">Payment Due Date</th>
            <th class="fw-bold">Payment Date</th>
            <th class="fw-bold">Payment Amount</th>
            <th class="fw-bold">Payment Status</th>
        </tr>
    </table>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("New Traffic Violation", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Traffic Violation Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Traffic Violation", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Delete/Cancel Traffic Violation", "Delete", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Review Citation Message", "CitationMessage", null, htmlAttributes: new { @class = "tts-nav" })
    </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 class='text-center'>" + ticket["TrafficViolationNumber"] + "</td>" +
                            "<td class='text-center'>" + ticket["CameraNumber"]           + "</td>" +
                            "<td class='text-center'>" + ticket["TagNumber"]              + "</td>" +
                            "<td>"                     + ticket["ViolationName"]          + "</td>" +
                            "<td class='text-center'>" + ticket["ViolationDate"]          + "</td>" +
                            "<td class='text-center'>" + ticket["ViolationTime"]          + "</td>" +
                            "<td class='text-center'>" + ticket["PhotoAvailable"]         + "</td>" +
                            "<td class='text-center'>" + ticket["VideoAvailable"]         + "</td>" +
                            "<td>"                     + ticket["PaymentDueDate"]         + "</td>" +
                            "<td>"                     + ticket["PaymentDate"]            + "</td>" +
                            "<td>"                     + ticket["PaymentAmount"]          + "</td>" +
                            "<td>"                     + ticket["PaymentStatus"]          + "</td></tr>");
                    });
                }
            });
        });
    </script>
  17. Click the TrafficViolationController.cs tab

Creating a Traffic Violation

A traffic violation is a process with many steps. To start, when an infraction has been committed, a user must create a record. We will start such a process with an appropriate webform.

Practical LearningPractical Learning: Creating a Traffic Violation

  1. In the TrafficViolationController class, right-click one of the Create() methods and click Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Create

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Create Traffic Ticket";
    }
    
    <h2 class="text-center fw-bold common-font">Traffic Violation - New Traffic Ticket</h2>
    
    <hr />
    
    <form name="frmCreateTrafficViolation" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="trafViolNbr" class="col-md-36 top-padding">Traffic Violation #:</label>
                <div class="col-md-64"><input type="text" id="trafViolNbr" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="cameraNumber" class="col-md-36 top-padding">Camera #:</label>
                <div class="col-md-64">
                    <input type="text" id="cameraNumber" class="form-control camera-number" />
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-36 top-padding">Camera Details:</label>
                <div class="col-md-64">
                    <span id="cameraDetails" class="camera-details"></span>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="vehicleTagNbr" class="col-md-36 top-padding">Vehicle Tag #:</label>
                <div class="col-md-64">
                    <input type="text" id="vehicleTagNbr" class="form-control vehicle-tag-number" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">Vehicle Details:</label>
                <div class="col-md-64">
                    <span id="vehicleDetails" name="vehicleDetails"></span>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">Owner/Driver:</label>
                <div class="col-md-64">
                    <span id="ownerName" name="ownerName"></span>
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-36"></label>
                <div class="col-md-64">
                    <span id="ownerAddress" name="ownerAddress"></span>
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-36"></label>
                <div class="col-md-64">
                    <span id="ownerCityState" name="ownerCityState"></span>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="category" class="col-md-36 top-padding">Violation Type:</label>
                <div class="col-md-64">
                    <select id="category" class="form-control"></select>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="county" class="col-md-36 top-padding">Violation Date:</label>
                <div class="col-md-64"><input type="date" id="trafficDate" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="trafficTime" class="col-md-36 top-padding">Violation Time:</label>
                <div class="col-md-64"><input type="time" id="trafficTime" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="photo" class="col-md-36 top-padding">Photo Available:</label>
                <div class="col-md-64">
                    <select id="photo" class="form-control">
                        <option value="No">No</option>
                        <option value="Yes">Yes</option>
                    </select>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="photo" class="col-md-36 top-padding">Video Available:</label>
                <div class="col-md-64">
                    <select id="video" class="form-control">
                        <option value="No">No</option>
                        <option value="Yes">Yes</option>
                    </select>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="pdd" class="col-md-36 top-padding">Payment Due Date:</label>
                <div class="col-md-64"><input type="date" id="pdd" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="pmtDate" class="col-md-36 top-padding">Payment Date:</label>
                <div class="col-md-64"><input type="date" id="pmtDate" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="pmtAmt" class="col-md-36 top-padding">Payment Amount:</label>
                <div class="col-md-64"><input type="text" id="pmtAmt" class="form-control" /></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="pmtStatus" class="col-md-36 top-padding">Video Available:</label>
                <div class="col-md-64">
                    <select id="pmtStatus" class="form-control">
                        <option value="Pending">Pending</option>
                        <option value="Rejected">Rejected</option>
                        <option value="Cancelled">Cancelled</option>
                        <option value="Paid Late">Paid Late</option>
                        <option value="Paid On Time">Paid On Time</option>
                    </select>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">&nbsp;</label>
                <div class="col-md-64">
                    <input type="button" id="btnCreateTicket" class="btn btn-primary" value="Save Traffic Violation" />
                </div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Traffic Violation Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Traffic Violation", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Cancel Traffic Violation", "Delete", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Review Citation Message", "Citation Message", null, htmlAttributes: new { @class = "tts-nav" })
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            var drvLicNbr = "";
    
            $.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>");
                    });
                }
            });
    
            $(".camera-number").blur(function (event) {
                $.ajax({
                    method: "GET",
                    dataType: "json",
                    url: "/api/Cameras",
                    success: function (data) {
                        $.each(data, function (index, device) {
                            if (device["CameraNumber"] === $(".camera-number").val()) {
                                $(".camera-details").text(device["Make"] + " " +
                                    device["Model"] + " (Location: " +
                                    device["Location"] + ")");
                            }
                        });
                    }
                });
            }); // Camera Number Lost Focus
    
            $(".vehicle-tag-number").blur(function (event) {
                $.ajax({
                    method: "GET",
                    dataType: "json",
                    url: "/api/Vehicles",
                    success: function (data) {
                        $.each(data, function (index, vehicle) {
                            if (vehicle["TagNumber"] === $(".vehicle-tag-number").val()) {
                                drvLicNbr = vehicle["DrvLicNumber"];
    
                                $("span[name='vehicleDetails']").text(vehicle["Make"] + " " +
                                    vehicle["Model"] + " (" +
                                    vehicle["VehicleYear"] + ", " + vehicle["Color"] + ")");
                            }
                        });
    
                        FindOwner();
                    }
                });
            }); // Vehicle Tag Number Lost Focus
    
            function FindOwner() {
                $.ajax({
                    method: "GET",
                    dataType: "json",
                    url: "/api/Drivers/",
                    success: function (data) {
                        $.each(data, function (index, person) {
                            if (person["DrvLicNumber"] === drvLicNbr) {
                                $("span[name='ownerName']").text(person["FirstName"] + " " +
                                    person["LastName"]);
                                $("span[name='ownerAddress']").text(person["Address"]);
                                $("span[name='ownerCityState']").text(person["City"] + ", " +
                                    person["State"] + " " +
                                    person["ZIPCode"]);
                            }
                        });
    
                    }
                });
            }
    
            $("#btnCreateTicket").click(function () {
                var ticket = {
                    TrafficViolationNumber: $("#trafViolNbr").val(),
                    CameraNumber:           $("#cameraNbr").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(),
                    PaymentStatus:          $("#pmtStatus").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>
  5. Click the TrafficViolationController.cs tab
  6. To execute, on the main menu, click Debug -> Start Without Debugging

    Traffic Tickets System - Home Page

  7. Click the Traffic Violations link:

    Traffic Tickets System - Vehicles Registrations

  8. Click the New Traffic Violation link

    Traffic Tickets System - New Vehicle Registration

  9. In the Web controls, enter or select the following values and click the Save button after each:
    Traffic Violation # Camera # Tag # Violation Type Violation Date Violation Time Photo Available Video Available Payment Due Date Payment Date Payment Amount Payment Status
    68469242 MSR-59575 KLT4805 Stop Sign 01/18/2020 09:12 AM Yes Yes 02/28/2020 02-27-2020 75 Paid On Time

    Traffic Tickets System - New Traffic Violation

  10. Click the Save Traffic Violation:

    Traffic Tickets System - New Traffic Violationn

  11. Once again, click the New Traffic Violation link
  12. In the Web controls, enter or select the following values:
    29727048 DHT-29417 971384 Speed 02/06/2020 19:04 PM No Yes 04-05-2020 03-31-2020 85 Paid On Time
    Click the Save Traffic Violation button
  13. Return to your programming environment
  14. In the Server Explorer, right-click TrafficTicketsSystem1 and click New Query
  15. In the empty document, type the following code:
    INSERT INTO TrafficViolations(TrafficViolationNumber, CameraNumber, TagNumber, ViolationName, 
    							  ViolationDate, ViolationTime, PhotoAvailable, VideoAvailable, 
    							  PaymentDueDate, PaymentDate, PaymentStatus)
    VALUES(N'42717297', N'DGH-38460', N'PER2849', N'Red Light Steady', N'01/31/2020', N'05:15:18', N'Yes', N'No', N'03/10/2020', N'125', N'Pending'),
    	  (N'47827081', N'AHR-41518', N'MWH4685', N'Speed',            N'03-31-2020', N'22:07:31', N'Yes', N'No', N'02-28-2020', N'60', N'Pending');
    GO
    INSERT INTO TrafficViolations(TrafficViolationNumber, CameraNumber, TagNumber, ViolationName, 
    							  ViolationDate, ViolationTime, PhotoAvailable, VideoAvailable,
    							  PaymentDueDate, PaymentDate, PaymentAmount, PaymentStatus)
    VALUES(N'47183148', N'MSR-59575', N'8DE9275', N'Stop Sign', N'01/18/2020', N'14:22:48', N'No', N'Yes', N'03/10/2020', N'03/27/2020', N'90', N'Paid Late');
    GO
    INSERT INTO TrafficViolations(TrafficViolationNumber, CameraNumber, TagNumber, ViolationName,
    							  ViolationDate, ViolationTime, PhotoAvailable, VideoAvailable,
    							  PaymentDueDate, PaymentDate, PaymentStatus)
    VALUES(N'26850869', N'ELQ-79284', N'KLT4805', N'Speed', N'04-12-2020', N'08:16:22', N'No', N'Yes', N'06-08-2020', N'100', N'Cancelled');
    GO
    INSERT INTO TrafficViolations(TrafficViolationNumber, CameraNumber, TagNumber, ViolationName,
    							  ViolationDate, ViolationTime, PhotoAvailable, VideoAvailable,
    							  PaymentDueDate, PaymentDate, PaymentAmount, PaymentStatus)
    VALUES(N'37920479', N'HTR-93847', N'PER2849', N'Red Light Flashing',   N'01/28/2020', N'22:14:53', N'No',  N'No',  N'03/02/2020', N'03-01-2020', N'45', N'Rejected'),
    	  (N'82424140', N'DGH-38460', N'KAS9314', N'Red Light Right Turn', N'01/31/2020', N'12:30:11', N'Yes', N'No',  N'02-28-2020', N'04-02-2020', N'90', N'Paid Late'),
    	  (N'44808258', N'DHT-29417', N'FKEWKR',  N'Speed',                N'03/05/2020', N'16:07:15', N'No',  N'Yes', N'04/22/2020', N'04/15/2020', N'85', N'Paid On Time'),
    	  (N'74806976', N'DHT-29417', N'971384',  N'Speed',                N'02/06/2020', N'11:58:06', N'No',  N'Yes', N'04/05/2020', N'03/31/2020', N'85', N'Paid On Time');
    GO
    INSERT INTO TrafficViolations(TrafficViolationNumber, CameraNumber, TagNumber, ViolationName,
    							  ViolationDate, ViolationTime, PhotoAvailable, VideoAvailable,
    							  PaymentDueDate, PaymentDate, PaymentStatus)
    VALUES(N'59718502', N'ELQ-79284', N'8DE9275', N'Speed', N'04-15-2020', N'15:25:53', N'Yes', N'No', N'06/02/2020', N'40', N'Pending');
    GO
  16. To execute, on the SQL Editor toolbar, click the Execute button Execute
  17. Close the Query window
  18. When asked whether you want to save, click No
  19. Click the TrafficViolationController.cs tab

Reviewing a Traffic Violation

At any time, a user may want to review the details of a traffic violation. To help the user get such information, we will create a form.

Practical LearningPractical Learning: Viewing the Details of a Vehicle

  1. In the TrafficViolationController class, right-click inside the Details() method and click Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Details

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Violation/Infraction Details";
    }
    
    <h2 class="text-center fw-bold common-font">Violation/Infraction Details</h2>
    
    <hr />
    
    <form name="frmDetailsTrafficViolation" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="cameraId" class="col-md-36 top-padding">Violation Id:</label>
                <div class="col-md-2"><input type="text" id="infractionId" class="form-control" /></div>
                <div class="col-md-4">
                    <input type="button" id="btnShowViolation"
                           class="btn btn-primary" value="Find Traffic Violation" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Traffic Violation #:</label>
                <div class="col-md-64">
                    <span name="traffic-violation-number" class="form-control"></span>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Camera:</label>
                <div class="col-md-64"><span name="camera" class="form-control"></span></div>
            </div>
    
            <input type="hidden" id="btnFindCamera" value="Find Camera" />
    
            <div class="form-group row">
                <label class="col-md-36">Camera Details:</label>
                <div class="col-md-64">
                    <span id="cameraDetails" name="cameraDetails"></span>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Vehicle Tag #:</label>
                <div class="col-md-64"><span name="vehicleTagNbr" class="form-control"></span></div>
            </div>
    
            <input type="hidden" id="btnFindVehicle" value="Find Vehicle" />
            <input type="hidden" id="btnFindOwner" value="Find Owner" />
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">Vehicle Details:</label>
                <div class="col-md-64">
                    <span id="vehicleDetails" name="vehicleDetails"></span>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">Owner/Driver:</label>
                <div class="col-md-64">
                    <span id="ownerName" name="ownerName"></span>
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-36"></label>
                <div class="col-md-64">
                    <span id="ownerAddress" name="ownerAddress"></span>
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-36"></label>
                <div class="col-md-64">
                    <span id="ownerCityState" name="ownerCityState"></span>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Violation Type:</label>
                <div class="col-md-64"><span name="category" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Violation Date:</label>
                <div class="col-md-64"><span name="date-of-infraction" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Violation Time:</label>
                <div class="col-md-64"><span name="time-of-infraction" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Photo is Available:</label>
                <div class="col-md-64"><span name="steady-photo-available" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Video is Available:</label>
                <div class="col-md-64"><span name="streaming-video-available" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Payment Due Date:</label>
                <div class="col-md-64"><span name="payment due date" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Payment Date:</label>
                <div class="col-md-64"><span name="last-day-payment" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Amount Owed:</label>
                <div class="col-md-64"><span name="amount-owed" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Payment Status:</label>
                <div class="col-md-64"><span name="payment-status" class="form-control"></span></div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("New Traffic Violation", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Traffic Violation", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Delete/Cancel Traffic Violation", "Delete", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Preview Citation Message", "CitationMessage", null, htmlAttributes: new { @class = "tts-nav" })
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $(".btn-primary").on("click", function (event) {
                var tagNumber = "";
                var drvLicNbr = "";
                var cameraNumber = "";
    
                $.ajax({
                    method: "GET",
                    dataType: "json",
                    url: "/api/TrafficViolations/" + $("#infractionId").val(),
                    success: function (data) {
                        $("span[name$='traffic-violation-number']").text(data.TrafficViolationNumber);
                        $("span[name$='camera']").text(data.CameraNumber);
                        cameraNumber = data.CameraNumber;
                        $("span[name$='vehicleTagNbr']").text(data.TagNumber);
                        tagNumber = 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);
                        $("span[name='payment-status']").text(data.PaymentStatus);
    
                        FindCamera();
                        FindVehicle();
                        FindOwner();
                    }
                });
    
                $("#btnFindCamera").on("click", function (event) {
                    FindCamera();
                });
    
                $("#btnFindVehicle").on("click", function (event) {
                    FindVehicle();
                });
    
                $("#btnFindOwner").on("click", function (event) {
                    FindOwner();
                });
    
                function FindCamera() {
                    $.ajax({
                        url: "/api/Cameras/",
                        method: "GET",
                        dataType: "json",
                        success: function (data) {
                            $.each(data, function (index, device) {
                                if (device["CameraNumber"] === cameraNumber) {
                                    $("span[name='cameraDetails']").text(device.Location + " (" +
                                        device.Make + " " + device.Model + ")");
                                }
                            });
                        }
                    });
                }
    
                function FindVehicle() {
                    $.ajax({
                        method: "GET",
                        dataType: "json",
                        url: "/api/Vehicles/",
                        success: function (data) {
                            $.each(data, function (index, vehicle) {
                                if (vehicle["TagNumber"] === tagNumber) {
                                    drvLicNbr = vehicle["DrvLicNumber"];
                                    $("span[name='vehicleDetails']").text(vehicle["VehicleYear"] + " " +
                                        vehicle["Make"] + " " +
                                        vehicle["Model"] + ", " +
                                        vehicle["Color"]);
                                }
                            });
                        }
                    });
                }
    
                function FindOwner() {
                    $.ajax({
                        method: "GET",
                        dataType: "json",
                        url: "/api/Drivers/",
                        success: function (data) {
                            $.each(data, function (index, person) {
                                if (person["DrvLicNumber"] === drvLicNbr) {
                                    $("span[name='ownerName']").text(person["FirstName"] + " " +
                                        person["LastName"]);
                                    $("span[name='ownerAddress']").text(person["Address"]);
                                    $("span[name='ownerCityState']").text(person["City"] + ", " +
                                        person["State"] + " " +
                                        person["ZIPCode"]);
                                }
                            });
    
                        }
                    });
                }
            });
        });
    </script>
  5. Click the TrafficViolationController.cs tab
  6. To execute, on the main menu, click Debug -> Start Without Debugging
  7. Click the Traffic Violations link:

    Traffic Tickets System - Vehicles Registrations

  8. Click the Traffic Violation Details link:

    Traffic Tickets System - Vehicle Details

  9. In the Violation Id text box, type 9
  10. Click the Find Traffic Violation button:

    Traffic Tickets System - Violations Type Details

  11. Return to your programming environment

Updating a Traffic Violation

A traffic violation is like a living document. Any of its information can change any time. To assist the user, we will create a webform that can be used to update the details of a traffic violation.

Practical LearningPractical Learning: Updating a Traffic Violation

  1. In the TrafficViolationController class, right-click one of the Edit() methods -> Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Edit:

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Edit/Update Violation Details";
    }
    
    <h2 class="text-center fw-bold common-font">Edit/Update Violation Details</h2>
    
    <hr />
    
    <form name="frmTrafficViolationDetails" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="infractionId" class="col-md-36 top-padding">Violation Id:</label>
                <div class="col-md-2"><input type="text" id="infractionId" class="form-control" /></div>
                <div class="col-md-4">
                    <input type="button" id="btnFindTrafficViolation" 
                           class="btn btn-primary" value="Find Traffic Violation" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="trafViolNbr" class="col-md-36 top-padding">Traffic Violation #:</label>
                <div class="col-md-64">
                    <input type="text" id="trafficViolationNbr" name="trafficViolationNbr" class="form-control" />
                </div>
            </div>
    
            <hr />
            <div class="form-group row">
                <label for="cmrNbr" class="col-md-36 top-padding">Camera #:</label>
                <div class="col-md-64">
                    <input type="text" id="cameraNumber" name="cameraNumber" class="form-control" />
                </div>
            </div>
    
            <input type="hidden" id="btnFindCamera" value="Find Camera" />
    
            <div class="form-group row">
                <label class="col-md-36">Camera Location:</label>
                <div class="col-md-64">
                    <span id="cameraDetails" name="cameraDetails"></span>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="vehicleTagNbr" class="col-md-36 top-padding">Vehicle Tag #:</label>
                <div class="col-md-64">
                    <input type="text" id="vehicleTagNbr"
                           name="vehicleTagNbr" class="form-control" />
                </div>
            </div>
    
            <input type="hidden" id="btnFindVehicle" value="Find Vehicle" />
            <input type="hidden" id="btnFindOwner" value="Find Owner" />
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">Vehicle Details:</label>
                <div class="col-md-64">
                    <span id="vehicleDetails" name="vehicleDetails"></span>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36">Owner/Driver:</label>
                <div class="col-md-64">
                    <span id="ownerName" name="ownerName"></span>
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-36"></label>
                <div class="col-md-64">
                    <span id="ownerAddress" name="ownerAddress"></span>
                </div>
            </div>
            <div class="form-group row">
                <label class="col-md-36"></label>
                <div class="col-md-64">
                    <span id="ownerCityState" name="ownerCityState"></span>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="category" class="col-md-36 top-padding">Violation Type:</label>
                <div class="col-md-64">
                    <select id="category" name="category" class="form-control">
                        <option value="Unknown"></option>
                    </select>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="county" class="col-md-36 top-padding">Violation Date:</label>
                <div class="col-md-64">
                    <input id="violationDate" name="violationDate" class="form-control" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="trafficTime" class="col-md-36 top-padding">Violation Time:</label>
                <div class="col-md-64">
                    <input type="time" id="violationTime" name="violationTime" class="form-control" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="photo" class="col-md-36 top-padding">Photo Available:</label>
                <div class="col-md-64">
                    <select id="photo" name="photoAvailable" class="form-control">
                        <option value="No">No</option>
                        <option value="Yes">Yes</option>
                    </select>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="photo" class="col-md-36 top-padding">Video Available:</label>
                <div class="col-md-64">
                    <select id="video" name="videoAvailable" class="form-control">
                        <option value="No">No</option>
                        <option value="Yes">Yes</option>
                    </select>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="pdd" class="col-md-36 top-padding">Payment Due Date:</label>
                <div class="col-md-64">
                    <input id="paymentDueDate" name="paymentDueDate" class="form-control" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="pmtDate" class="col-md-36 top-padding">Payment Date:</label>
                <div class="col-md-64">
                    <input id="paymentDate" name="paymentDate" class="form-control" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="pmtAmt" class="col-md-36 top-padding">Payment Amount:</label>
                <div class="col-md-64">
                    <input type="text" id="paymentAmt" name="paymentAmt" class="form-control" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label for="pmtStatus" class="col-md-36 top-padding">Payment Status:</label>
                <div class="col-md-64">
                    <select id="paymentStatus" name="paymentStatus" class="form-control">
                        <option value="Pending">Pending</option>
                        <option value="Rejected">Rejected</option>
                        <option value="Cancelled">Cancelled</option>
                        <option value="Paid Late">Paid Late</option>
                        <option value="Paid On Time">Paid On Time</option>
                    </select>
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">&nbsp;</label>
                <div class="col-md-64">
                    <input type="button" id="btnUpdateViolation"
                           class="btn btn-primary" value="Update Violation/Ticket Details" />
                </div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Process New Violation", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Traffic Violation Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Scrap Traffic Violation", "Delete", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Review Citation Message", "CitationMessage", null, htmlAttributes: new { @class = "tts-nav" })
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnFindTrafficViolation").on("click", function (event) {
                var tagNumber = "";
                var drvLicNbr = "";
                var cameraNumber = "";
    
                $.ajax({
                    method: "GET",
                    dataType: "json",
                    url: "/api/TrafficViolations/" + $("#infractionId").val(),
                    success: function (data) {
                        $("input[name='trafficViolationNbr']").val(data.TrafficViolationNumber);
                        $("input[name$='cameraNumber']").val(data.CameraNumber);
                        cameraNumber = data.CameraNumber;
                        $("input[name$='vehicleTagNbr']").val(data.TagNumber);
                        tagNumber = data.TagNumber;
                        $("select[name$='category']").val(data.ViolationName);
                        $("input[name|='violationDate']").val(data.ViolationDate);
                        $("input[name|='violationTime']").val(data.ViolationTime);
                        $("select[name*='photoAvailable']").val(data.PhotoAvailable);
                        $("select[name*='videoAvailable']").val(data.VideoAvailable);
                        $("input[name~='paymentDueDate']").val(data.PaymentDueDate);
                        $("input[name='paymentDate']").val(data.PaymentDate);
                        $("input[name='paymentAmt']").val(data.PaymentAmount);
                        $("select[name='paymentStatus']").val(data.PaymentStatus);
    
                        FindCamera();
                        FindVehicle();
                        FindOwner();
                    }
                });
    
                $("#btnFindCamera").on("click", function (event) {
                    FindCamera();
                });
    
                function FindCamera() {
                    $.ajax({
                        method: "GET",
                        dataType: "json",
                        url: "/api/Cameras/",
                        success: function (data) {
                            $.each(data, function (index, device) {
                                if (device["CameraNumber"] === cameraNumber) {
                                    $("span[name='cameraDetails']").text(device.Location + " (" +
                                        device.Make + " " + device.Model + ")");
                                }
                            });
                        }
                    });
                }
    
                function FindVehicle() {
                    $.ajax({
                        method: "GET",
                        dataType: "json",
                        url: "/api/Vehicles/",
                        success: function (data) {
                            $.each(data, function (index, vehicle) {
                                if (vehicle["TagNumber"] === tagNumber) {
                                    drvLicNbr = vehicle["DrvLicNumber"];
                                    $("span[name='vehicleDetails']").text(vehicle["VehicleYear"] + " " +
                                        vehicle["Make"] + " " +
                                        vehicle["Model"] + ", " +
                                        vehicle["Color"]);
                                }
                            });
                        }
                    });
                }
    
                function FindOwner() {
                    $.ajax({
                        method: "GET",
                        dataType: "json",
                        url: "/api/Drivers/",
                        success: function (data) {
                            $.each(data, function (index, person) {
                                if (person["DrvLicNumber"] === drvLicNbr) {
                                    $("span[name='ownerName']").text(person["FirstName"] + " " +
                                        person["LastName"]);
                                    $("span[name='ownerAddress']").text(person["Address"]);
                                    $("span[name='ownerCityState']").text(person["City"] + ", " +
                                        person["State"] + " " +
                                        person["ZIPCode"]);
                                }
                            });
    
                        }
                    });
                }
    
                $.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>");
                        });
                    }
                });
            });
    
            $("input[name$='cameraNumber']").blur(function (event) {
                $.ajax({
                    method: "GET",
                    dataType: "json",
                    url: "/api/Cameras/",
                    success: function (data) {
                        $.each(data, function (index, device) {
                            if (device["CameraNumber"] === $("#cameraNumber").val()) {
                                $("span[name='cameraDetails']").text(device.Location + " (" +
                                    device.Make + " " + device.Model + ")");
                            }
                        });
                    }
                });
            }); // Camera Number Lost Focus
    
            $("input[name$='vehicleTagNbr']").blur(function (event) {
                var drvLicNbr = "";
    
                $.ajax({
                    method: "GET",
                    dataType: "json",
                    url: "/api/Vehicles/",
                    success: function (data) {
                        $.each(data, function (index, vehicle) {
                            if (vehicle["TagNumber"] === $("input[name$='vehicleTagNbr']").val()) {
                                drvLicNbr = vehicle["DrvLicNumber"];
                                $("span[name='vehicleDetails']").text(vehicle["VehicleYear"] + " " +
                                    vehicle["Make"] + " " +
                                    vehicle["Model"] + ", " +
                                    vehicle["Color"]);
                            }
                        });
                    }
                });
    
                $.ajax({
                    method: "GET",
                    dataType: "json",
                    url: "/api/Drivers/",
                    success: function (data) {
                        $.each(data, function (index, person) {
                            if (person["DrvLicNumber"] === drvLicNbr) {
                                $("span[name='ownerName']").text(person["FirstName"] + " " +
                                    person["LastName"]);
                                $("span[name='ownerAddress']").text(person["Address"]);
                                $("span[name='ownerCityState']").text(person["City"] + ", " +
                                    person["State"] + " " +
                                    person["ZIPCode"]);
                            }
                        });
    
                    }
                });
            }); // Vehicle Tag Number Lost Focus
    
            $("#btnUpdateViolation").click(function (event) {
                var ticket = {
                    TrafficViolationNumber: $("input[name='trafficViolationNbr']").val(),
                    TrafficViolationId:     $("#infractionId").val(),
                    CameraNumber: $("input[name$='cameraNumber']").val(),
                    TagNumber: $("input[name$='vehicleTagNbr']").val(),
                    ViolationName: $("select[name$='category']").val(),
                    ViolationDate: $("input[name|='violationDate']").val(),
                    ViolationTime: $("input[name|='violationTime']").val(),
                    PhotoAvailable: $("select[name*='photoAvailable']").val(),
                    VideoAvailable: $("select[name*='videoAvailable']").val(),
                    PaymentDueDate: $("input[name~='paymentDueDate']").val(),
                    PaymentDate: $("input[name='paymentDate']").val(),
                    PaymentAmount: $("input[name='paymentAmt']").val(),
                    PaymentStatus: $("select[name='paymentStatus']").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>
  5. Click the TrafficViolationController.cs tab
  6. To execute, on the main menu, click Debug -> Start Without Debugging
  7. Click the Traffic Violations link:

    Traffic Tickets System - Traffic Violations

  8. Click the Edit/Update Traffic Violation link:

    Traffic Tickets System - Edit/Update Traffic Violation

  9. In the Violation Id text box, type 9
  10. Click the Find Traffic Violation button:

    Traffic Tickets System - Violations Type Details

  11. In the Violation Id text box, change the value to 3
  12. Click the Find Vehicle button:

    Traffic Tickets System - Violations Type Details

  13. Change the information of some of the Vehicles as follows:
    Traffic Violation #:  400004
    Camera #:             DHT-29417
    Vehicle Tag #:        MWH4685
    Violation Type:       Red Light Right Turn
    Violation Date:       01/22/2025
    Violation Time:       10:26 PM
    Photo Available:      No
    Video Available:      Yes
    Payment Due Date:     02/24/2025
    Payment Date:         03/31/2025
    Payment Amount:       155
    Payment Status:       Paid On Time
  14. Click the Updare Violation/Ticket Details:

    Traffic Tickets System - Traffic Violations

  15. Return to your programming environment

Deleting a Traffic Violation

For some a reason, an application can decide to cancel or delete a traffic violation. When this happen, we will equip our application with a form that can be used to delete a traffic violation.

Practical LearningPractical Learning: Deleting a Traffic Violation

  1. In the TrafficViolationController class, right-click one of the Delete() methods and click Add View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying Delete:

    Add View

    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Delete Traffic Violation";
    }
    
    <h2 class="text-center fw-bold common-font">Delete Traffic Violation</h2>
    
    <hr />
    
    <form name="frmTrafficViolationDeletion" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="cameraId" class="col-md-36 top-padding">Violation Id:</label>
                <div class="col-md-32"><input type="text" id="infractionId" class="form-control" /></div>
                <div class="col-md-32">
                    <input type="button" id="btnShowViolation" class="btn btn-primary finding" value="Show the Violation" />
                </div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Traffic Violation #:</label>
                <div class="col-md-64"><span name="traffic-violation-number" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Camera:</label>
                <div class="col-md-64"><span name="camera" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Vehicle Tag #:</label>
                <div class="col-md-64"><span name="vehicle" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Violation Type:</label>
                <div class="col-md-64"><span name="vioType" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Violation Date:</label>
                <div class="col-md-64"><span name="date-of-infraction" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Violation Time:</label>
                <div class="col-md-64"><span name="time-of-infraction" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Photo is Available:</label>
                <div class="col-md-64"><span name="steady-photo-available" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Video is Available:</label>
                <div class="col-md-64"><span name="streaming-video-available" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Payment Due Date:</label>
                <div class="col-md-64"><span name="payment due date" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Payment Date:</label>
                <div class="col-md-64"><span name="last-day-payment" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Amount Owed:</label>
                <div class="col-md-64"><span name="amount-owed" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <div class="form-group row">
                <label class="col-md-36 top-padding">Payment Status:</label>
                <div class="col-md-64"><span name="payment-status" class="form-control"></span></div>
            </div>
    
            <hr />
    
            <h3 class="common-font text-center">Are you sure you want to delete or cancel this citation?</h3>
    
            <div class="form-actions no-color text-center">
                <input type="submit" value="Delete Traffic Violation" class="btn btn-primary deletion" />
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("New Traffic Violation", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Traffic Violation Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Traffic Violation", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Preview Citation Message", "Citation Messasge", null, htmlAttributes: new { @class = "tts-nav" })
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            $(".finding").on("click", function (event) {
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url:      "/api/TrafficViolations/" + $("#infractionId").val(),
                    success: function (data) {
                        $("span[name$='traffic-violation-number']").text(data.TrafficViolationNumber);
                        $("span[name$='camera']").text(data.CameraNumber);
                        $("span[name$='vehicle']").text(data.TagNumber);
                        $("span[name$='vioType']").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);
                        $("span[name='payment-status']").text(data.PaymentStatus);
                    }
                });
            });
    
            $(".deletion").click(function (event) {
                var citation = {
                    TrafficViolationId: $("#infractionId").val()
                };
    
                $.ajax({
                    method:                 "DELETE",
                    url:                    "/api/TrafficViolations/" + $("#infractionId").val(),
                    data:                   citation,
                    success: function (data) {
                        alert("The traffic violation has been deleted.")
    
                        window.location.href = 'Index';
                    }
                });
            });
        });
    </script>
  5. Click the TrafficViolationController.cs tab
  6. To execute, on the main menu, click Debug -> Start Without Debugging
  7. Click the Traffic Violations link:

    Traffic Tickets System - Traffic Violations

  8. Click the Delete Traffic Violation link:

    Traffic Tickets System - Traffic Violation Deletion

  9. In the Violation Id text box, type 7
  10. Click the Find Traffic Violation button:

    Traffic Tickets System - Traffic Camera Removal

  11. Click the Delete Traffic Violation button:

    Traffic Tickets System - Delete Violation Type

  12. Click OK on the message box:

    Traffic Tickets System - Traffic Cameras

  13. Return to your programming environment

A Traffic Violation Message

When a road traffic violation has been committed and registered, a message (or citation) can be sent to the driver. It is a document that contains various pieces of information. We will create such a message as a webpage in our application.

Practical LearningPractical Learning: Creating a Traffic Violation Message

  1. In the TrafficViolationController class, right-click any part of the CitationMessage() method -> Add -> View...
  2. In the Add New Scaffolded Item dialog box, make sure MVC 5 View is selected:

    Add New Scaffolded Item

    Click Add
  3. In the Add View dialog box, make sure the View Name text box is displaying CitationMessage.
    Click Add
  4. Change the document as follows:
    @{
        ViewBag.Title = "Citation Message";
    }
    
    <h2 class="text-center fw-bold common-font">Citation Message</h2>
    
    <form name="TrafficViolations" method="post">
        <div class="box-holder common-font">
            <div class="form-group row">
                <label for="cameraId" class="col-md-36 top-padding">Violation Id:</label>
                <div class="col-md-32"><input type="text" id="infractionId" class="form-control" /></div>
                <div class="col-md-32">
                    <input type="button" id="btnPreviewCitation" class="btn btn-primary" value="Preview the Citation" />
                </div>
            </div>
        </div>
    
        <hr />
    
        <div class="common-font">
            <h3 class="fw-bold text-center">City of Jamies Town</h3>
            <h6 class="text-center fw-bold">6824 Cochran Ave, Ste 318<br />Jamies Town, MD 20540</h6>
    
            <hr />
    
            <div class="row">
                <div class="col-md-64">
                    <table>
                        <tr>
                            <td style="width: 200px"><h6 class="fw-bold">Citation #:</h6></td>
                            <td><span name="traffic-violation-number"></span></td>
                        </tr>
                        <tr>
                            <td><h6 class="fw-bold">Camera #:</h6></td>
                            <td><span name="camera-number"></span></td>
                        </tr>
                        <tr>
                            <td><h6 class="fw-bold">Camera Location:</h6></td>
                            <td><span name="camera-location"></span></td>
                        </tr>
                        <tr>
                            <td><h6 class="fw-bold">Violation Type:</h6></td>
                            <td><span name="violation-name"></span> Violation</td>
                        </tr>
                    </table>
    
                    <hr />
    
                    <h5 class="fw-bold">Vehicle</h5>
    
                    <table>
                        <tr>
                            <td style="width: 200px"><h6 class="fw-bold">Tag #:</h6></td>
                            <td><span name="tag-number"></span></td>
                        </tr>
                        <tr>
                            <td><h6 class="fw-bold">Description:</h6></td>
                            <td><span name="vehicle-identification"></span></td>
                        </tr>
                    </table>
    
                    <hr />
    
                    <h5 class="fw-bold">Registered Owner</h5>
    
                    <table>
                        <tr>
                            <td style="width: 200px"><h6 class="fw-bold">Driver's License #:</h6></td>
                            <td><span name="drivers-license-number"></span></td>
                        </tr>
                        <tr>
                            <td><h6 class="fw-bold">Registered To:</h6></td>
                            <td><span name="driver-name"></span></td>
                        </tr>
                        <tr>
                            <td><h6 class="fw-bold">Address:</h6></td>
                            <td><span name="driver-address"></span></td>
                        </tr>
                    </table>
    
                    <hr />
    
                    <p>Our records indicate that on <span class="fw-bold" name="violation-date"></span> at <span name="violation-time" class="fw-bold"></span>, at <span name="camera-location" class="fw-bold"></span>, the above mentioned vehicle committed a <span class="fw-bold" name="violation-name"></span> violation.</p>
    
                    <p>If you recognize the traffic violation, please pay $<span name="payment-amount" class="fw-bold"></span> by <span name="payment-due-date" class="fw-bold"></span>. Failure to pay the amount by that date will result in an increase of the fine and could result in the suspension of your driving priviledges. If you dispute the violation, to eventually appear in court, please fill out the form on the back of this document and send it back to us.</p>
                </div>
                <div class="col-md-36 top-padding">
                    <p><span name="photo-video"></span></p>
                </div>
            </div>
        </div>
    </form>
    
    <hr />
    
    <p class="text-center">
        @Html.ActionLink("Traffic Violations", "Index", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("New Traffic Violation", "Create", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Traffic Violation Details", "Details", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Edit/Update Traffic Violation", "Edit", null, htmlAttributes: new { @class = "tts-nav" }) ::
        @Html.ActionLink("Delete/Cancel Traffic Violation", "Delete", null, htmlAttributes: new { @class = "tts-nav" })
    </p>
    
    @Scripts.Render("~/bundles/jquery")
    
    <script type="text/javascript">
        $(document).ready(function () {
            var cameraNbr = "";
            var drvLicNbr = "";
            var vehicleTagNbr = "";
    
            var getPhotoVideoOptions = function(photo, video) {
                var sentence = "";
                var pvAvailable = "No";
    
                if (photo === "Yes") {
                    if (video === "Yes") {
                        pvAvailable = "Yes";
                        sentence = "To view the photo and/or video";
                    } else {
                        pvAvailable = "Yes";
                        sentence = "To see a photo";
                    }
                } else { // if (photo === "No")
                    if (video === "Yes") {
                        pvAvailable = "Yes";
                        sentence = "To review a video";
                    } else {
                        pvAvailable = "No";
                    }
                }
    
                if (pvAvailable === "No")
                    return "There is no photo or video available of this infraction but the violation was committed.";
                else
                    return sentence + " of this violation, please access http://www.trafficviolationsmedia.com. In the form, enter the citation number and click Submit.";
            }
    
            $(".btn-primary").on("click", function (event) {
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url:      "/api/TrafficViolations/" + $("#infractionId").val(),
                    success: function (data) {
                        $("span[name$='traffic-violation-number']").text(data.TrafficViolationNumber);
                        $("span[name$='violation-name']").text(data.ViolationName);
                        $("span[name$='camera-number']").text(data.CameraNumber);
                        cameraNbr = data.CameraNumber;
                        $("span[name$='tag-number']").text(data.TagNumber);
                        vehicleTagNbr = data.TagNumber;
                        $("span[name|='violation-date']").text(data.ViolationDate);
                        $("span[name|='violation-time']").text(data.ViolationTime);
                        $("span[name='payment-amount']").text(data.PaymentAmount);
                        $("span[name~='payment-due-date']").text(data.PaymentDueDate);
    
                        $("span[name$='photo-video']").text(getPhotoVideoOptions(data.PhotoAvailable, data.VideoAvailable));
                    }
                });
    
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url:      "/api/Cameras",
                    success: function (data) {
                        $.each(data, function (index, camera) {
                            if (camera["CameraNumber"] === cameraNbr) {
                                $("span[name|='camera-location']").text(camera["Location"]);
                            }
                        });
                    }
                });
    
                $.ajax({
                    method:   "GET",
                    dataType: "json",
                    url:      "/api/Vehicles",
                    success: function (data) {
                        $.each(data, function (index, vehicle) {
                            if (vehicle["TagNumber"] === vehicleTagNbr) {
                                $("span[name$='drivers-license-number']").text(vehicle["DrvLicNumber"]);
                                drvLicNbr = vehicle["DrvLicNumber"];
                                $("span[name$='vehicle-identification']").text(vehicle["VehicleYear"] + ", " +
                                                                               vehicle["Make"] + " " +
                                                                               vehicle["Model"] + ", " +
                                                                               vehicle["Color"]);
                            }
                        });
                    }
                });
    
                $.ajax({
                    method: "GET",
                    dataType: "json",
                    url: "/api/Drivers",
                    success: function (data) {
                        $.each(data, function (index, person) {
                            if (person["DrvLicNumber"] === drvLicNbr) {
                                $("span[name$='driver-name']").text(person["FirstName"] + " " +
                                                                    person["LastName"]);
                                $("span[name$='driver-address']").text(person["Address"] + " " +
                                    person["City"] + ", " +
                                    person["State"] + " " +
                                    person["ZIPCode"]);
                            }
                        });
                    }
                });
            });
        });
    </script>
  5. Click the TrafficViolationController.cs tab
  6. To execute the application to test it, on the main menu, click Debug and click Start Without Debugging
  7. Click the Traffic Violations link

  8. Click the bottom Review Citation Message link

    Traffic Tickets System

  9. In the Violation Id text box, type 1
  10. Click the Preview the Citation button

    Traffic Tickets System - Edit/Update Camera Information

  11. In the Violation Id text box, replace the value with 7
  12. Click the Preview the Citation button

    Traffic Tickets System

  13. Close the browser and return to your programming environment
  14. Close your programming environment

Home Copyright © 2017-2025, FunctionX Monday 13 January 2025, 11:09 Home