I am trying, on button click, to get the JSON version of my View Model from the value attribute or data attribute, and send it to my controller where it updates the model. Then with the new model send that to the view and have the process repeat if a button is clicked again.
The problem I am having is that the model reverts back to the original one, whenever my JS code tries to grab the updated model. It never can grab the update model that is passed into the view.
I would appreciate it if anyone could help me solve this problem!
Index.cshtml
@model BlujayProject.Models.ViewModels.IndexVM
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Blujay Truck Control</title>
<script src="https://kit.fontawesome.com/c263a03295.js"
crossorigin="anonymous"></script>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z"
crossorigin="anonymous" />
<link rel="stylesheet" href="/css/indexStyles.css" />
</head>
<body>
@{
BlujayProject.Models.ViewModels.IndexVM viewModelObject = @Model;
var jsonVMO = Json.Serialize(viewModelObject);
}
<div class="text-center">
<img class="responsiveLogo" src="~/images/BluJaySolutionsLogo.png" />
</div>
<div class="row text-center m-5">
<div class="col-6 border rounded-left p-5 mainBorderStyles">
<img src="/images/redLight.png" class="responsiveSemi" />
</div>
<div class="col-6 border rounded-right p-5 mainBorderStyles">
<img src="/images/Semi.png" class="responsiveSemi" />
</div>
</div>
<div class="row text-center">
<div class="col-6 btn-group-lg">
<button class="btn btn-danger btn-lg trafficButton" value=@jsonVMO id="redLight" onclick="getID(this.id);">
Red
</button>
<button class="btn btn-warning btn-lg trafficButton" value=@jsonVMO id="yellowLight" onclick="getID(this.id);">
Yellow
</button>
<button class="btn btn-success btn-lg trafficButton" value=@jsonVMO id="greenLight" onclick="getID(this.id);">
Green!
</button>
<button class="btn btn-outline-success btn-lg trafficButton" value=@jsonVMO id="greenLTurn" onclick="getID(this.id);">
Left Turn
</button>
</div>
<div class="col-6 btn-group-lg">
<button class="btn btn-primary btn-lg truckButton" type="submit" data-test=@jsonVMO value=@jsonVMO id="leftTurn" onclick="getID(this.id);">
Turn Left
</button>
<button class="btn btn-success btn-lg truckButton" type="submit" data-test=@jsonVMO value=@jsonVMO id="moveForward" onclick="getID(this.id);">
Drive
</button>
<button class="btn btn-danger btn-lg truckButton" type="submit" data-test=@jsonVMO value=@jsonVMO id="jackKnifeToStop" onclick="getID(this.id);">
Stop!
</button>
<button class="btn btn-primary btn-lg truckButton" type="submit" data-test=@jsonVMO value=@jsonVMO id="rightTurn" onclick="getID(this.id);">
Turn Right
</button>
</div>
</div>
<div hidden>
<div class="text-center mt-5">
<h2>@Model.vehicleStrategy.StateDescription.Replace("_", " ")</h2>
</div>
<div class="text-center">
<h2>@Model.signalStrategy.StateDescription.Replace("_", " ")</h2>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
<script>
// Get the current year for the copyright
$("#year").text(new Date().getFullYear());
</script>
<script src="/js/indexScript.js"></script>
</body>
HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using BlujayProject.Models;
using BlujayProject.Models.ViewModels;
using BlujayProject.Models.VehicleInterfaces;
using BlujayProject.Models.Interfaces.SigInterfaces;
namespace BlujayProject.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
Vehicle semiTruck;
Signal trafficLight;
IndexVM indexVM;
public HomeController(ILogger<HomeController> logger)
{
indexVM = new IndexVM();
semiTruck = new SemiTruck();
trafficLight = new TrafficLight();
_logger = logger;
}
public IActionResult Index(/*IndexVM indexVM*/)
{
indexVM = InitializeIndexView(indexVM);
trafficLight = new TrafficLight();
return View(indexVM);
}
#region Privacy View and Other Action Methods
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
#endregion
[HttpPost]
public ActionResult GetTruckButtonCommands(IndexVM indexVM)
{
if(ValidateSemiTruckResponse(indexVM))
{
indexVM.vehicleStrategy = PerformVehicleCommand(indexVM.StateOfAction, semiTruck);
}
return View("Index", indexVM);
}
[HttpPost]
public ActionResult GetTrafficLButtonCommands(IndexVM indexVM)
{
indexVM.signalStrategy = PerformSignalCommand(indexVM.StateOfAction, trafficLight);
return View("Index", indexVM);
}
#region State Changes and Operation Logic
public VehicleStrategyModel PerformVehicleCommand(string vehicleCommand, Vehicle vehicle)
{
switch (vehicleCommand)
{
case "rightTurn":
vehicle.performRightTurnAct();
break;
case "leftTurn":
vehicle.performLeftTurnAct();
break;
case "moveForward":
vehicle.performDriveAct();
break;
case "jackKnifeToStop":
vehicle.performStopAct();
break;
}
vehicle.VehicleStrategyModel.StateDescription = vehicle.VehicleStrategyModel.StateDescription.Replace(" ", "_");
return vehicle.VehicleStrategyModel;
}
public SignalStrategyModel PerformSignalCommand(string signalCommand, Signal signal)
{
switch (signalCommand)
{
case "greenLight":
signal.performGoAct();
break;
case "greenLTurn":
signal.performSideShiftAct();
break;
case "yellowLight":
signal.performSlowShiftAct();
break;
case "redLight":
signal.performStopAct();
break;
}
signal.SignalStrategyModel.StateDescription = signal.SignalStrategyModel.StateDescription.Replace(" ", "_");
return signal.SignalStrategyModel;
}
public bool ValidateSemiTruckResponse(IndexVM indexVM)
{
string signalState = indexVM.signalStrategy.State;
string semiTruckCommand = indexVM.vehicleStrategy.State;
if (signalState == "greenLight" && semiTruckCommand == "moveforward")
{
//Generate Error
return false;
}
if(signalState == "greenLTurn" && semiTruckCommand != "leftTurn")
{
//Generate an error
return false;
}
if (signalState != "greenLTurn" && semiTruckCommand == "leftTurn")
{
//Generate an error
return false;
}
if (indexVM.StateOfAction == "moveForward")
{
if(semiTruckCommand == "moveForward")
{
return false;
}
}
if(indexVM.StateOfAction == "jackKnifeToStop")
{
if (semiTruckCommand == "jackKnifeToStop")
{
return false;
}
}
return true;
}
#endregion
public IndexVM InitializeIndexView(IndexVM indexVM)
{
if (indexVM.IsInitialized != true)
{
IndexVM indexVMInit = new IndexVM();
VehicleStrategyModel vehicleStrategyModel = new VehicleStrategyModel();
SignalStrategyModel signalStrategyModel = new SignalStrategyModel();
indexVMInit.vehicleStrategy = vehicleStrategyModel;
indexVMInit.signalStrategy = signalStrategyModel;
if (indexVMInit.signalStrategy.State == null)
{
indexVMInit.signalStrategy.State = "greenLight";
indexVMInit.signalStrategy.StateDescription = "This_light_is_green!";
}
if (indexVMInit.vehicleStrategy.State == null)
{
indexVMInit.vehicleStrategy.State = "neutral";
indexVMInit.vehicleStrategy.StateDescription = "The_vehicle_is_Ready_to_Go!";
}
indexVMInit.IsInitialized = true;
return indexVMInit;
}
return indexVM;
}
}
}
IndexScript.js
var truckImage, elementIDn, jsObject;
function updateValues(value) {
$(`#leftTurn`).val(value);
$(`#leftTurn`).data('value', value.val);
}
// This is a function I created to get the id of the HTML tag so that I wouldn't have to write duplicate code
function getID(id) {
/*console.log(id);*/
elementID = id;
return id;
}
$(document).ready(function () {
$('.truckButton').click(function () {
/* console.log($(`#${elementID}`).data("test"));
jsObject = $(`#${elementID}`).data("test");
$(`#${elementID}`).data('test', jsObject); */
jsObject = JSON.parse($(`#${elementID}`).val());
/*jsObject = JSON.parse(document.getElementById(`${elementID}`).getAttribute("value"));*/
//adjusting JavaScrpt objects has to be lower case when converting to .NET Model
jsObject.stateOfAction = `${elementID}`;
console.log(jsObject);
$.ajax({
type: 'POST',
dataType: 'application/json; charset=utf-8',
url: '/Home/GetTruckButtonCommands',
data: jsObject,
/*success: setTimeout(function () {// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 2000),*/
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
return false;
});
});
$(document).ready(function () {
$('.trafficButton').click(function () {
/*var jsObject = JSON.parse($("#willWork").val());*/
jsObject = JSON.parse(document.getElementById(`${elementID}`).value);
//adjusting JavaScrpt objects has to be lower case when converting to .NET Model
jsObject.stateOfAction = `${elementID}`;
console.log(jsObject);
$.ajax({
type: 'POST',
dataType: 'application/json; charset=utf-8',
url: '/Home/GetTrafficLButtonCommands',
data: jsObject,
success: function (response) {
response ? alert("It worked!") : alert("It didn't work.");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
return false;
});
});