Search code examples
javascriptc#asp.net-mvcviewbag

How to refresh the ViewBag?


I want to send either a 1 (New Code) or 0 (no New Code), but still the ViewBag only accepts the first value that is written to it.

Controller

        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>

I don't know how to fix that or if there is an other solution to this.

Similar questions: How To Change or refresh data using ViewBag in MVC3 (That tutorial didnt help me either)


Solution

  • Let assume your list contains 2 rows and during for iteration first time this if (list[i].BauTeilId.Equals(Code)) condition returns true and second time return false.

    Your loop will set newID value based on last iteration. In last iteration if if (list[i].BauTeilId.Equals(Code)) return 0 else 1.

    Check out below updated code :

        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;