P
P
password222021-08-21 02:17:25
JavaScript
password22, 2021-08-21 02:17:25

Data is not coming from js fetch to asp net, why?

Good evening! I'm trying to figure out how to send POST from js to asp net, but I haven't found anything ready on the Internet. I wrote myself. Now I can't figure out what's the problem...

I'm sending FormData data from Js, I receive them from IFormCollection, but the values ​​are empty

html

<div class="container">

    <h1>Регистрация на сайте</h1>

    <form action="#" method="post" id="form_UserRegistration">

        <label for="input_UserName">Имя</label>
        <input type="text" name="UserName" id="input_UserName" />

        <label for="input_UserEmail">Email</label>
        <input type="text" name="UserEmail" id="input_UserEmail" />

        <label for="input_UserAge">Возраст</label>
        <input type="number" name="UserAge" id="input_UserAge" />

        <button type="submit">Зарегистрироваться</button>

    </form>

</div>


JS
const form = document.getElementById('form_UserRegistration');

    form.addEventListener('submit', async function (e) {
        e.preventDefault();

        let response = await fetch('http://localhost:24068/home/index', {
            method: 'POST',
            body: new FormData(form),
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        });


        console.log(response.status);
        var formData = new FormData(form);
        for (var [key, value] of formData.entries()) {
            console.log(key, value);
        };

        return response.json;
    });


C#
[HttpPost]
        public async Task<JsonResult> Index(IFormCollection form)
        {
            return Json(new { name = form["UserName"], email = form["UserEmail"], age = form["UserAge"] });
        }


I tracked throughout the code the places where data is lost. In js, everything is fine, but when the answer comes, then all the values ​​​​are empty there. In the database, all fields are written as null

I will be glad for any help, thanks in advance

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
password22, 2021-08-21
@password22

Everything works, like this:
HTML

<div class="container">

    <h1>Регистрация на сайте</h1>

    <form action="#" method="post" id="form_UserRegistration">

        <label for="input_UserName">Имя</label>
        <input type="text" name="UserName" id="input_UserName" />

        <label for="input_UserEmail">Email</label>
        <input type="text" name="UserEmail" id="input_UserEmail" />

        <label for="input_UserAge">Возраст</label>
        <input type="number" name="UserAge" id="input_UserAge" />

        <button type="submit">Зарегистрироваться</button>

    </form>

</div>

JS
<script>

    const form = document.getElementById('form_UserRegistration');

    fetch('http://localhost:24068/home/index', {
        method: 'POST',
        body: JSON.stringify(Object.fromEntries(new FormData(form)))
    }).then(function (response) {
        // Стоит проверить код ответа.
        if (!response.ok) {
            // Сервер вернул код ответа за границами диапазона [200, 299]
            return Promise.reject(new Error(
                'Response failed: ' + response.status + ' (' + response.statusText + ')'
            ));
        }

        // Далее будем использовать только JSON из тела ответа.
        return response.json();
    }).then(function (data) {
        console.log(data);
    }).catch(function (error) {
        console.log(error);
    });

</script>

C# asp.net mvc
[HttpPost]
        public async Task<IActionResult> Index(IFormCollection form)
        {
            var createSql = @"INSERT INTO UsersTable (UserName, UserEmail, Age) VALUES (@UserName, @UserEmail, @Age)";

            var usersSql = @"SELECT * FROM UsersTable";

            using (var connection = new SqlConnection(CONNECTION_STRING))
            {
                var usersCreate = await connection.QueryAsync<UserModel>(createSql, new { @UserName = form["UserName"], @UserEmail = form["UserEmail"], @Age = form["UserAge"] });
                var usersTable = await connection.QueryAsync<UserModel>(usersSql);
                return View(usersTable);
            }
        }

S
SANTA2112, 2021-08-21
@SANTA2112

body:

JSON.stringify(Object.fromEntries(new FormData(form)))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question