skip to Main Content

Here’s a complete example of a .NET Core MVC application that simulates a traffic signal with dynamic settings for rotation duration and type.

Model (SignalModel.cs):

namespace TrafficSignalApp.Models
{
    public class SignalModel
    {
        public int Duration { get; set; }
        public string RotationType { get; set; }
        public string OpenRoad { get; set; }
        public string NextOpenRoad { get; set; }
        public int RemainTime { get; set; }
    }
}

View (Index.cshtml):

@model TrafficSignalApp.Models.SignalModel

@{
    ViewData["Title"] = "Traffic Signal";
}

<div class="container">
    <div class="config">
        <label asp-for="Duration">Time Duration (5-120 sec):</label>
        <input asp-for="Duration" min="5" max="120" value="15">
        <label asp-for="RotationType">Signal Rotation Type:</label>
        <select asp-for="RotationType">
            <option value="Clockwise">Clockwise</option>
            <option value="Anticlockwise">Anticlockwise</option>
            <option value="UpDown">Up to Down or Down to Up</option>
            <option value="LeftRight">Left to Right or Right to Left</option>
        </select>
        <button id="start">Start</button>
    </div>
    <div class="traffic-signal">
        <div class="road" id="A" style="background-color: @Model.OpenRoad == "A" ? "green" : "red"></div>
        <div class="road" id="B" style="background-color: @Model.OpenRoad == "B" ? "green" : "red"></div>
        <div class="road" id="C" style="background-color: @Model.OpenRoad == "C" ? "green" : "red"></div>
        <div class="road" id="D" style="background-color: @Model.OpenRoad == "D" ? "green" : "red"></div>
    </div>
    <div class="info">
        <p>Road Rotation Duration: <span id="infoDuration">@Model.Duration</span> Sec.</p>
        <p>Road Rotation Type: <span id="infoType">@Model.RotationType</span></p>
        <p>Open Road: <span id="infoOpenRoad">@Model.OpenRoad</span></p>
        <p>Next Open Road: <span id="infoNextRoad">@Model.NextOpenRoad</span></p>
        <p>Remain Time: <span id="infoRemainTime">@Model.RemainTime</span> Sec.</p>
    </div>
</div>

@section Scripts {
    <script src="~/js/script.js"></script>
}

Controller (SignalController.cs):

using Microsoft.AspNetCore.Mvc;
using TrafficSignalApp.Models;

namespace TrafficSignalApp.Controllers
{
    public class SignalController : Controller
    {
        public IActionResult Index()
        {
            var model = new SignalModel
            {
                Duration = 15, // Default duration
                RotationType = "Clockwise", // Default rotation type
                OpenRoad = "A", // Default open road
                NextOpenRoad = "B", // Default next open road
                RemainTime = 5 // Default remaining time
            };

            return View(model);
        }
    }
}

JavaScript (wwwroot/js/script.js):

$(document).ready(function () {
    var rotationDuration = parseInt($("#infoDuration").text());
    var rotationType = $("#infoType").text();
    var openRoad = $("#infoOpenRoad").text();
    var remainTime = parseInt($("#infoRemainTime").text());
    var timeInterval;
    var timeDuration = 1000; // Default time duration in milliseconds

    function updateInfo() {
        $("#infoDuration").text(rotationDuration);
        $("#infoType").text(rotationType);
        $("#infoOpenRoad").text(openRoad);
        // Calculate the next open road
        var roadOrder = ["A", "B", "C", "D"];
        var currentIndex = roadOrder.indexOf(openRoad);
        var nextIndex =
            rotationType === "Clockwise"
                ? (currentIndex + 1) % roadOrder.length
                : rotationType === "Anticlockwise"
                ? (currentIndex - 1 + roadOrder.length) % roadOrder.length
                : rotationType === "UpDown"
                ? currentIndex % 2 === 0
                    ? (currentIndex + 2) % roadOrder.length
                    : (currentIndex + 1) % 2 === 0
                    ? (currentIndex - 1 + roadOrder.length) % roadOrder.length
                    : currentIndex
                : rotationType === "LeftRight"
                ? currentIndex % 2 === 0
                    ? (currentIndex + 1) % 2 === 0
                        ? (currentIndex - 2 + roadOrder.length) % roadOrder.length
                        : (currentIndex + 1) % roadOrder.length
                    : (currentIndex + 2) %

 roadOrder.length
                : currentIndex;
        $("#infoNextRoad").text(roadOrder[nextIndex]);
        $("#infoRemainTime").text(remainTime);
    }

    function switchLights() {
        $(".road").removeClass("green");
        $("#" + openRoad).addClass("green");
    }

    function rotateRoad() {
        var roadOrder = ["A", "B", "C", "D"];
        var currentIndex = roadOrder.indexOf(openRoad);

        switchLights();

        currentIndex =
            rotationType === "Clockwise"
                ? (currentIndex + 1) % roadOrder.length
                : rotationType === "Anticlockwise"
                ? (currentIndex - 1 + roadOrder.length) % roadOrder.length
                : rotationType === "UpDown"
                ? currentIndex % 2 === 0
                    ? (currentIndex + 2) % roadOrder.length
                    : (currentIndex + 1) % 2 === 0
                    ? (currentIndex - 1 + roadOrder.length) % roadOrder.length
                    : currentIndex
                : rotationType === "LeftRight"
                ? currentIndex % 2 === 0
                    ? (currentIndex + 1) % 2 === 0
                        ? (currentIndex - 2 + roadOrder.length) % roadOrder.length
                        : (currentIndex + 1) % roadOrder.length
                    : (currentIndex + 2) % roadOrder.length
                : currentIndex;
        openRoad = roadOrder[currentIndex];
        remainTime = rotationDuration;
        updateInfo();
    }

    function startSignal() {
        $("#start").prop("disabled", true);

        timeInterval = setInterval(function () {
            if (remainTime > 0) {
                remainTime--;
                updateInfo();
            } else {
                rotateRoad();
            }
        }, timeDuration);
    }

    $("#start").click(function () {
        rotationDuration = parseInt($("#infoDuration").text());
        rotationType = $("#infoType").text();
        updateInfo();
        switchLights();
        startSignal();
    });
});

This code sets up a dynamic traffic signal in a .NET Core MVC application with settings for rotation duration and type. The JavaScript code handles the dynamic rotation based on the selected type. The view allows users to configure these settings.

2

Answers


  1. Chosen as BEST ANSWER

    You can save this into database using below code snippet,

    To capture traffic rotation details in a database and handle the insertion of records with the start and end times, you can follow these steps:

    1. Create a SQL Server database and a table to store the rotation details. Here's a sample SQL script to create the table:
    CREATE TABLE TrafficSignalRotations
    (
        ID INT IDENTITY(1,1) PRIMARY KEY,
        RotationType VARCHAR(50),
        OpenRoad CHAR(1),
        NextOpenRoad CHAR(1),
        TimeDuration INT,
        StartTime DATETIME,
        EndTime DATETIME
    );
    
    1. Modify the C# code in your .NET Core MVC controller to insert and update records in the database. You'll need to use Entity Framework Core for database operations. If you haven't already, install Entity Framework Core and configure it in your project.

    Controller (SignalController.cs):

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using System;
    using System.Linq;
    using TrafficSignalApp.Models;
    
    namespace TrafficSignalApp.Controllers
    {
        public class SignalController : Controller
        {
            private readonly AppDbContext _context;
    
            public SignalController(AppDbContext context)
            {
                _context = context;
            }
    
            public IActionResult Index()
            {
                var model = new SignalModel
                {
                    Duration = 15, // Default duration
                    RotationType = "Clockwise", // Default rotation type
                    OpenRoad = "A", // Default open road
                    NextOpenRoad = "B", // Default next open road
                    RemainTime = 5 // Default remaining time
                };
    
                return View(model);
            }
    
            [HttpPost]
            public IActionResult StartSignal(SignalModel model)
            {
                if (ModelState.IsValid)
                {
                    var rotation = new TrafficSignalRotation
                    {
                        RotationType = model.RotationType,
                        OpenRoad = model.OpenRoad,
                        NextOpenRoad = model.NextOpenRoad,
                        TimeDuration = model.Duration,
                        StartTime = DateTime.Now
                    };
    
                    _context.TrafficSignalRotations.Add(rotation);
                    _context.SaveChanges();
    
                    return RedirectToAction("Index");
                }
    
                return View("Index", model);
            }
    
            [HttpPost]
            public IActionResult EndSignal()
            {
                var lastRotation = _context.TrafficSignalRotations.LastOrDefault();
                if (lastRotation != null && lastRotation.EndTime == null)
                {
                    lastRotation.EndTime = DateTime.Now;
                    _context.SaveChanges();
                }
    
                return RedirectToAction("Index");
            }
        }
    }
    
    1. Create an AppDbContext class to configure the Entity Framework context for your application.

    DbContext (AppDbContext.cs):

    using Microsoft.EntityFrameworkCore;
    
    namespace TrafficSignalApp.Models
    {
        public class AppDbContext : DbContext
        {
            public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
            {
            }
    
            public DbSet<TrafficSignalRotation> TrafficSignalRotations { get; set; }
        }
    }
    
    1. Modify your Startup.cs to configure the database connection and Entity Framework services. Make sure you've added the required NuGet packages for Entity Framework and your database provider.

    Startup.cs:

    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using TrafficSignalApp.Models;
    
    public class Startup
    {
        // ...
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
            // ...
        }
    
        // ...
    }
    
    1. In your appsettings.json, specify the connection string for your database.

    appsettings.json:

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=YourServer;Database=YourDatabase;Trusted_Connection=True;MultipleActiveResultSets=true"
      },
      // ...
    }
    

    With these modifications, the traffic signal rotation details will be stored in the database, and records will be updated with the end time when a new rotation starts.

    Pass Data from view to controller to database:

    To pass data from your view to your controller using AJAX and jQuery, you can create a JavaScript function that collects the data from the HTML elements and sends it to the server. Here's how you can do it:

    1. Add a button or link in your view that will trigger the AJAX request. For example:
    <button id="updateDataButton" class="btn btn-primary">Update Data</button>
    
    1. Create a JavaScript function in your view that collects the data from the HTML elements and sends it to the server. Use jQuery for the AJAX request. In your view, add a script section to include the JavaScript code:
    <script>
        $(document).ready(function () {
            $("#updateDataButton").click(function () {
                // Collect data from HTML elements
                var duration = $("#infoDuration").text();
                var rotationType = $("#infoType").text();
                var openRoad = $("#infoOpenRoad").text();
                var nextOpenRoad = $("#infoNextRoad").text();
                var remainTime = $("#infoRemainTime").text();
    
                // Create an object to hold the data
                var data = {
                    Duration: duration,
                    RotationType: rotationType,
                    OpenRoad: openRoad,
                    NextOpenRoad: nextOpenRoad,
                    RemainTime: remainTime
                };
    
                // Send the data to the server using AJAX
                $.ajax({
                    type: "POST",
                    url: "/YourController/UpdateData", // Replace with your controller and action
                    data: data,
                    success: function (response) {
                        // Handle the response from the server, if needed
                    },
                    error: function (error) {
                        // Handle any errors, if needed
                    }
                });
            });
        });
    </script>
    
    1. In your controller, create an action to handle the data update. For example:
    [HttpPost]
    public IActionResult UpdateData(SignalModel data)
    {
        // Update the data in your application, e.g., save it to the database
        // You can access data.Duration, data.RotationType, etc., to get the data passed from the view.
    
        // Return a response, if needed
        return Json(new { success = true });
    }
    

    In the example above, when the "Update Data" button is clicked, the JavaScript function collects data from the HTML elements and sends it to the UpdateData action in your controller using AJAX. The action processes the data, and you can return a response back to the client if needed. Make sure to replace "/YourController/UpdateData" with the actual URL of your controller action.


  2. Below Start Button :

    <button id="stop">Stop</button>
    

    The startSignal function in your JavaScript code initiates the signal rotation based on the timeDuration you’ve configured. If you want to add a "Stop" functionality, you can modify the code as follows:

    let signalRunning = false;
    let signalInterval;
    
    function startSignal() {
        if (!signalRunning) {
            $("#start").prop("disabled", true);
            signalRunning = true;
    
            signalInterval = setInterval(function () {
                if (remainTime > 0) {
                    remainTime--;
                    updateInfo();
                } else {
                    rotateRoad();
                }
            }, timeDuration);
        }
    }
    
    function stopSignal() {
        if (signalRunning) {
            $("#start").prop("disabled", false);
            clearInterval(signalInterval);
            signalRunning = false;
        }
    }
    
    $("#start").click(function () {
        startSignal();
    });
    
    $("#stop").click(function () {
        stopSignal();
    });
    

    In this modified code:

    1. We’ve added a signalRunning variable to track whether the signal is currently running or stopped.

    2. The startSignal function is now only invoked if the signal is not already running. It sets signalRunning to true and initiates the signal rotation.

    3. The stopSignal function clears the interval and sets signalRunning to false. This effectively stops the signal rotation when the "Stop" button is clicked.

    4. The "Stop" button click event now calls the stopSignal function to stop the signal when the button is clicked.

    This modification allows you to start and stop the signal rotation as needed by preventing multiple simultaneous starts and ensuring that the signal is stopped when the "Stop" button is clicked.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search