在.NET Core MVC中创建交通信号应用程序

6rqinv9w  于 2023-11-20  发布在  .NET
关注(0)|答案(2)|浏览(133)

下面是一个完整的.NET Core MVC应用程序示例,它模拟了一个交通信号灯,并对旋转持续时间和类型进行了动态设置。

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

字符串

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

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


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

1aaf6o9v

1aaf6o9v1#

开始按钮下方:

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

字符串
JavaScript代码中的startSignal函数根据您配置的timeDuration启动信号旋转。如果您想添加“停止”功能,可以如下修改代码:

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变量来跟踪信号当前是正在运行还是停止。

  1. startSignal函数现在仅在信号尚未运行时调用。它将signalRunning设置为true并启动信号旋转。
  2. stopSignal功能清除间隔,并将signalRunning设置为false。当点击“停止”按钮时,这将有效地停止信号旋转。
    1.“Stop”按钮单击事件现在调用stopSignal函数来在单击按钮时停止信号。
    此修改允许您根据需要启动和停止信号旋转,防止多个同时启动,并确保单击“停止”按钮时停止信号。
4urapxun

4urapxun2#

您可以使用下面的代码片段将其保存到数据库中,
要在数据库中捕获流量轮换详细信息并处理插入包含开始和结束时间的记录,您可以执行以下步骤:
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,请在项目中对其进行配置。

控制器(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.创建一个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.修改您的Startup.cs以配置数据库连接和Entity Framework服务。请确保已为Entity Framework和数据库提供程序添加所需的NuGet包。

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.在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将其发送到控制器中的UpdateData操作。该操作处理数据,如果需要,您可以将响应返回给客户端。请确保将“/YourController/UpdateData”替换为控制器操作的实际URL。

相关问题