在 .NET Core MVC 中创建交通信号应用程序Create Traffic Signal Application in .NET Core MVC

Create Traffic Signal Application in .NET Core MVC

提问人:parth patel 提问时间:11/1/2023 更新时间:11/1/2023 访问量:41

问:

下面是 .NET Core MVC 应用程序的完整示例,该应用程序使用旋转持续时间和类型的动态设置来模拟交通信号。

模型(信号模型.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; }
    }
}

视图 (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>
}

控制器(信号控制器 .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();
    });
});

此代码在 .NET Core MVC 应用程序中设置动态交通信号,并设置轮换持续时间和类型。JavaScript 代码根据所选类型处理动态旋转。该视图允许用户配置这些设置。

JavaScript C# .NET

评论


答:

0赞 parth patel 11/1/2023 #1

您可以使用以下代码片段将其保存到数据库中,

若要在数据库中捕获流量轮换详细信息并处理包含开始和结束时间的记录插入,可以执行以下步骤:

  1. 创建一个 SQL Server 数据库和一个表来存储轮换详细信息。下面是用于创建表的示例 SQL 脚本:
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. 修改 .NET Core MVC 控制器中的 C# 代码,以在数据库中插入和更新记录。需要使用 Entity Framework Core 进行数据库操作。如果尚未安装,请安装 Entity Framework Core 并在项目中对其进行配置。

控制器(信号控制器 .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. 创建一个类来配置应用程序的实体框架上下文。AppDbContext

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. 修改 your 以配置数据库连接和 Entity Framework 服务。请确保已为实体框架和数据库提供程序添加了所需的 NuGet 包。Startup.cs

启动.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. 在 中,指定数据库的连接字符串。appsettings.json

appsettings.json:

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

通过这些修改,交通信号灯旋转的详细信息将存储在数据库中,并且记录将在新的旋转开始时使用结束时间进行更新。

将数据从视图传递到控制器再到数据库:

若要使用 AJAX 和 jQuery 将数据从视图传递到控制器,可以创建一个 JavaScript 函数,该函数从 HTML 元素收集数据并将其发送到服务器。这是你如何做到的:

  1. 在视图中添加一个按钮或链接,以触发 AJAX 请求。例如:
<button id="updateDataButton" class="btn btn-primary">Update Data</button>
  1. 在视图中创建一个 JavaScript 函数,该函数从 HTML 元素收集数据并将其发送到服务器。将 jQuery 用于 AJAX 请求。在视图中,添加脚本部分以包含 JavaScript 代码:
<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. 在控制器中,创建一个操作来处理数据更新。例如:
[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 });
}

在上面的示例中,当单击“更新数据”按钮时,JavaScript 函数会从 HTML 元素中收集数据,并使用 AJAX 将其发送到控制器中的操作。该操作处理数据,如果需要,您可以将响应返回给客户端。请确保将“/YourController/UpdateData”替换为控制器操作的实际 URL。UpdateData

0赞 parth patel 11/1/2023 #2

在“开始”按钮下方:

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

JavaScript 代码中的函数会根据您配置的如果要添加“停止”功能,可以按如下方式修改代码:startSignaltimeDuration

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();
});

在此修改后的代码中:

  1. 我们添加了一个变量来跟踪信号当前是正在运行还是已停止。signalRunning

  2. 现在,仅当信号尚未运行时,才会调用该函数。它设置并启动信号旋转。startSignalsignalRunningtrue

  3. 该函数清除间隔并设置为 。当单击“停止”按钮时,这有效地停止了信号旋转。stopSignalsignalRunningfalse

  4. “停止”按钮单击事件现在调用函数以在单击按钮时停止信号。stopSignal

此修改允许您根据需要启动和停止信号旋转,防止多个同时启动并确保在单击“停止”按钮时停止信号。