Mail.ruПочтаМой МирОдноклассникиВКонтактеИгрыЗнакомстваНовостиКалендарьОблакоЗаметкиВсе проекты

Помогите пожалуйста с asp.net

ы ы Знаток (451), открыт 3 недели назад
public class RegistrationModel : PageModel
{

List<User> usersList = new List<User>();
public void OnGet()
{
}

public IActionResult OnPost()
{
try
{
using (var reader = new StreamReader(HttpContext.Request.Body))
{
var body = reader.ReadToEnd();
Console.WriteLine($"Received body: {body}");

if (string.IsNullOrEmpty(body))
{
return BadRequest(new { success = false, message = "Request body is empty." });
}

var user = JsonSerializer.Deserialize<User>(body);
if (user == null || string.IsNullOrEmpty( user.Name ) || string.IsNullOrEmpty(user.Password))
{
return BadRequest(new { success = false, message = "Invalid data." });
}


usersList.Add(user);
Console.WriteLine($"User added: { user.Name }");

return new JsonResult(new { success = true });
}
}
catch (Exception ex)
{

Console.WriteLine($"Error: {ex.Message}");
return StatusCode(500, new { success = false, message = "An error occurred." });
}
}

} function validateForm(event) {
event.preventDefault(); // Предотвращаем стандартное поведение формы


var password = document.getElementById("password").value;
var password1 = document.getElementById("password1").value;

if (password !== password1) {
alert("Пароли не совпадают. Пожалуйста, попробуйте снова.");
return; // Выходим из функции
}


var user = {
Name: document.getElementById("login").value,
Password: password
};

fetch('Registration', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(user)
})
.then(response => {
console.log('Response Status:', response.status); // Log status
return response.text().then(text => {
if (!response.ok) {
let errorMessage;
try {
const errorData = JSON.parse(text);
errorMessage = errorData.message || 'Error occurred';
} catch (e) {
errorMessage = text;
}
throw new Error(errorMessage);
}
return JSON.parse(text); // Parse the successful response
});
})
.then(data => {
console.log('Success:', data);
window.location.href = '/success';
})
.catch((error) => {
console.error('Error:', error);
}); public class User
{
public string Name { get; set; }
public string Password { get; set; }

public User() { }
}
1 ответ
S.H.I. Оракул (71333) 3 недели назад
Хранение пользователей (временно, для тестирования):
 public class RegistrationModel : PageModel  
{
private static readonly List<User> usersList = new List<User>(); // Статический список
}
Упрощенный метод OnPost с использованием модели:
 public IActionResult OnPost([FromBody] User user)  
{
try
{
if (user == null ||
string.IsNullOrEmpty(user.Name) ||
string.IsNullOrEmpty(user.Password))
{
return BadRequest(new { success = false, message = "Invalid data." });
}

usersList.Add(user);
Console.WriteLine($"User added: {user.Name}");

return new JsonResult(new { success = true });
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
return StatusCode(500, new { success = false, message = ex.Message });
}
}
Класс User с валидацией:
 public class User  
{
[Required]
[JsonPropertyName("name")]
public string Name { get; set; }

[Required]
[JsonPropertyName("password")]
public string Password { get; set; }
}
Исправленный JavaScript:
 function validateForm(event) { 
event.preventDefault();

const password = document.getElementById("password").value;
const password1 = document.getElementById("password1").value;

if (password !== password1) {
alert("Пароли не совпадают!");
return;
}

const user = {
name: document.getElementById("login").value,
password: password
};

fetch('/Registration', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user)
})
.then(async response => {
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Ошибка сервера');
}
return data;
})
.then(data => {
window.location.href = '/Success';
})
.catch(error => {
console.error('Error:', error);
alert(error.message);
});
}
ы ыЗнаток (451) 3 недели назад
JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
Похожие вопросы