Перенаправление на другую страницу после отправки формы ASP NETC#

Место общения программистов C#
Anonymous
Перенаправление на другую страницу после отправки формы ASP NET

Сообщение Anonymous »

Я хочу перенаправить пользователя на другую страницу после отправки формы. У меня есть страница «Создать», на которой пользователь вводит данные, и «Обучение» с данными просмотра. Посмотреть

Код: Выделить всё

@model Deck















Create new module
Создать

Title





[h4]1[/h4]


Term


Definition 








+ Add card







script.js

Код: Выделить всё

var currentCardNumber = 1;

function addCard() {

currentCardNumber++;
let newCardHTML = `

[h4]${currentCardNumber}[/h4]


Term


Definition 



 `;
let newCard = document.createElement('div');
newCard.classList.add('card');
newCard.classList.add('mt-3');
newCard.innerHTML = newCardHTML;

let addNewCard = document.querySelector('.cards');
let referenceNode = document.getElementById('create-cards');
addNewCard.insertBefore(newCard, referenceNode);

}
function saveCardDataToServer() {
let cards = [];
document.querySelectorAll('.cards > .card   ').forEach((card) => {

let termInput = card.querySelector('input[name="term"]');
let definitionInput = card.querySelector('input[name="definition"]');

if (termInput &&  definitionInput) {
let term = termInput.value.trim();
let definition = definitionInput.value.trim();
cards.push({
Term: term,
Definition: definition
});
}
else {
console.error("Input elements not found in card:", card);
}
})

fetch('/Cards/Create/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({Cards: cards})
})
.then(response => response.json())
.then((data => {
if (data.success) {
console.log("Data successfully saved: ", data);
window.location.href = "/Cards/Learning";
} else {
console.error("Error saving card: ", data.message);
}
}))
}
document.addEventListener('DOMContentLoaded', function() {
let newCard = document.querySelector('.new-card');
newCard.addEventListener('click', function() {
addCard();
});
document.querySelector('form.cards').addEventListener('submit', function() {
saveCardDataToServer();
});
});
Контроллер

Код: Выделить всё

public class CardsController : Controller
{
public IActionResult Learning()
{
var cards = CardsRepository.GetCards();
return View(cards);
}

public IActionResult Create()
{
return View();
}

[HttpPost]
[Route("Cards/Create/")]
public IActionResult Create([FromBody] Deck deck)

{
if (deck != null && deck.Cards != null)
{
foreach (var card in deck.Cards)
{
if (!string.IsNullOrWhiteSpace(card.Term) && !string.IsNullOrWhiteSpace(card.Definition))
{
CardsRepository.AddCard(card);
}
}
return Json(new { success = true, message = "Card saved successfully " });
}
return Json(new {
success = false, message = "Invalid data provided"
});
}

}
Модели

Код: Выделить всё

public class Deck
{
public List Cards { get; set; }

public Deck()
{
Cards = new List();
}
}

public class Card
{
public int CardId { get; set; }
[Required]
public string Term { get; set; } = string.Empty;
public string Definition { get; set; } = string.Empty;
}
Я попробовал в представлении и document.getElementById('create-cards').addEventListener('click',function (){ window.location.href = "/Create/Learning"; }); в js это бесполезно.
Странная вещь, когда я отправляю форму с точкой останова при выборке в отладчик все работает правильно

Подробнее здесь: https://stackoverflow.com/questions/787 ... rm-asp-net

Вернуться в «C#»