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
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:
Controller (SignalController.cs):
AppDbContext
class to configure the Entity Framework context for your application.DbContext (AppDbContext.cs):
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:
appsettings.json
, specify the connection string for your database.appsettings.json:
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:
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.Below Start Button :
The
startSignal
function in your JavaScript code initiates the signal rotation based on thetimeDuration
you’ve configured. If you want to add a "Stop" functionality, you can modify the code as follows:In this modified code:
We’ve added a
signalRunning
variable to track whether the signal is currently running or stopped.The
startSignal
function is now only invoked if the signal is not already running. It setssignalRunning
totrue
and initiates the signal rotation.The
stopSignal
function clears the interval and setssignalRunning
tofalse
. This effectively stops the signal rotation when the "Stop" button is clicked.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.