Answer the question
In order to leave comments, you need to log in
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>
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;
});
[HttpPost]
public async Task<JsonResult> Index(IFormCollection form)
{
return Json(new { name = form["UserName"], email = form["UserEmail"], age = form["UserAge"] });
}
Answer the question
In order to leave comments, you need to log in
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>
<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>
[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);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question