0

I am currently working on a project but I have been stuck here for a day now. In summary the question I have depends only on the StartPage of my Project.

I have looked through countless guides even on StackOverflow but to no avail.


HTML

<!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>249765876358312345655</h1>

    @using (Html.BeginForm())
    {
    <p>
        Enter a Machine Code:
        <br />
        <input id="Code"
               name="Code"
               pattern=""
               size="30"
               spellcheck="false"
               title="Maschine Code"
               value="">
        <input type="hidden" value="26" name="projectId" />
    </p>


    <script>
            let x = document.getElementById("Code");
        x.addEventListener('input', function (event) {
            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) {

                window.location.href = '/home/Kontrolle';
                document.getElementById("Code").innerHTML = "";
                localStorage.setItem("Code_Kurz", stringDigits);


                $.ajax({
                    url: "@Url.Action("StartPage")",
                    type: "GET",
                    data: JSON.stringify(stringDigits),
                    dataType: "string",
                    contentType:"StartPage/json",
                    success: function (data) { alert("Succ: " + data); },
                    error: function (xhr, status, error) {
                        var errorMessage = xhr.status + ': ' + xhr.statusText;
                        console.log("ERROR: " + errorMessage);},
                });

            }
        });


    </script>
    }
</body>


</html>

To sum that up: the h1 Tag is a example of this Code witch gets filtered by ReGex -> end result: 123456

The number 123456 is saved in stringDigits. Now I want to pass stringDigits to the Controller.


Controller

namespace Qualitätskontrolle.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public IActionResult StartPage(string Code)
        {
            Debug.WriteLine(Code);
            return View();
}
}
}

There in the StartPage Controller should the string then appear.

The result should be in the Output window: 123456 but I only get the error message from javascript.

7
  • What does the js error say? Commented Jul 16, 2019 at 8:59
  • Its just this line of code but I have no idea what could be wrong html error: function () { alert("ERROR" + data); }, I think it just cant pick up the stringDigits value. Commented Jul 16, 2019 at 9:00
  • 1
    try to add data in function error: function (data) { alert("ERROR" + data); } Commented Jul 16, 2019 at 9:01
  • Don't alert errors. Use console.log instead if you want to see some details about your errors. Commented Jul 16, 2019 at 9:05
  • 1
    @KlausK: alert is horrible to see what a JS object contains. It can only show text. If you want to log an object, use console.log. Commented Jul 16, 2019 at 9:08

4 Answers 4

2

There are several issue here.

  • You are returning View to an ajax call. You should probably return Json("Content", JsonRequestBehavior.AllowGet).
  • You are setting dataType: JSON.stringify(stringDigits). You can remove this bit
  • You are setting data: "string". It should be data: { Code: stringDigits }, because StartPage expects parameter named Code as an input.
  • You are redirecting just before the AJAX window.location.href = '/home/Kontrolle' (Not sure why)
  • The error handler uses variable data that isn't defined in that context. Unlike success handler, the one for error does not receive data as an input. Here is an example of a correct error handling:

    error: function (xhr, status, error) {
        var errorMessage = xhr.status + ': ' + xhr.statusText;
        console.log("ERROR: " + errorMessage);
    }
    

There are several simple examples here: ASP.NET MVC controller actions that return JSON or partial html

public ActionResult StartPage(string code) 
{ 
    return Json(new { foo="bar" });
}

In JS:

$.getJSON(url, { code: stringDigits },
    function(data) {
        alert(data.foo);
    }
);
Sign up to request clarification or add additional context in comments.

4 Comments

if you just copy the thing about error handling from my answer below, i'd remove mine, cause we go over similar things
@Andrei yours seems much more detailed. You should keep it
I merged them anyway, it makes more sense to have one complete answer than two partial ones
@adiga I have now tried your error handeling and it said: ERROR: 200: parsererror Note: stringDigits already has the correct number in it.
1

From your code, I found that you have provided stringDigits in dataType instead of the data property. Maybe this caused the problem. So, please correct that code like as follows,

dataType: "string",
data: JSON.stringify(stringDigits)

1 Comment

I did it but to now avail sadly.
0

So, I have now edited the start Question except the error. I know the answer:

"Try to remove contentType and dataType from Ajax parameters and let them be identified automatically" ~ Catalin

These two should be removed:

 dataType: "string",
contentType:"StartPage/json",

See: https://stackoverflow.com/a/16013156/11754349

Comments

0

you can use the ajax call or use a input hidden field that fill with your data and you can call action in controller use URL and pass data use the query string example http://www.domin.com/controller/action?data=1234567 in java script can call url use : window.location=Url;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.