我想发送 1 (新代码)或 0 (无新代码),但是ViewBag仍然只接受写入的第一个值
控制器
int timesRun = 0;
int newID;
private ApplicationDbContext Context = new ApplicationDbContext();
[HttpGet]
public IActionResult StartPage(string Code)
{
Debug.WriteLine("Start: " + Code);
//Select BauTeilId
var list = (from t in Context.Result select new { t.BauTeilId }).ToList();
//Checking if already exists
for (int i = 0; i < list.Count; i++)
{
if (Code != null)
{
if (list[i].BauTeilId.Equals(Code))
{
newID = 0;
Debug.WriteLine("Keine neue ID " + newID);
}
else
{
newID = 1;
Debug.WriteLine("Neue ID " + newID);
break;
}
Debug.WriteLine(list[i].BauTeilId);
}
}
ViewBag.newID = newID;
return View();
}
HTML
@{
ViewData["Title"] = "Home Page";
}
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Starter</title>
<style>
p {
margin-top: 30%;
margin-left: 20%;
margin-right: 20%;
font-family: Arial;
font-size: 25px;
text-align: center;
}
#Code {
border: 2px solid black;
}
</style>
</head>
<body>
<h1>Example Code: 249765876358312345655</h1>
<p>
Eingabe des Maschinen Codes:
<br />
<input id="Code"
name="Code"
pattern=""
size="30"
spellcheck="false"
title="Maschine Code"
value="">
</p>
@{
var data = ViewBag.newID;
if(data != null)
{
data = ViewBag.newID.ToString().ToLower();
}
}
<script>
var x = document.getElementById("Code");
x.addEventListener('input', function (event) {
//Getting the regex sorted out
x = document.getElementById("Code").value;
let vars = x;
let digits = vars.match(/^\d{13}(\d{6})\d{2}$/)[1];
let stringDigits = digits.toString();
if (stringDigits.length == 6 && vars.length == 21) {
//New ID or not
let newID = '@data'.toString().toLowerCase();
Boolean(newID);
alert(newID);
if (newID === '1') window.location.href = '/home/NewIDSettingsPage';
else if(newID === '0')window.location.href = '/home/Kontrolle';
else alert("ERROR");
//Send to Kontrolle
document.getElementById("Code").innerHTML = "";
localStorage.setItem("Code_Kurz", stringDigits);
localStorage.setItem("Code_Lang", x);
//Send Code to Controller
$.ajax({
url: "@Url.Action("StartPage")",
type: "GET",
data: {Code: stringDigits},
success: function (data) { console.log("Succ: " + data); },
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText;
console.log("ERROR: " + errorMessage);},
});}});
</script>
</body>
</html>
我不知道该如何解决,或者是否有其他解决方案。
类似的问题: How To Change or refresh data using ViewBag in MVC3 (该教程也没有帮助我)
答案 0 :(得分:1)
假设您的列表包含2行,并且在迭代过程中,此if (list[i].BauTeilId.Equals(Code))
条件第一次返回true,第二次返回false。
您的循环将根据上一次迭代设置newID值。在上一次迭代中,如果if (list[i].BauTeilId.Equals(Code))
返回0,否则返回1。
查看以下更新的代码:
if (Code != null)
{
if count > 0 will return 0 else return 1
if (list.Where(x => x.BauTeilId.Equals(Code)).Count() > 0)
{
newID = 0;
Debug.WriteLine("Keine neue ID " + newID);
}
else
{
newID = 1;
Debug.WriteLine("Neue ID " + newID);
}
}
//pass value in viewbag
ViewBag.newID = newID;