<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"] });
}
<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);
}
}