response
- это переменная на стороне клиента, содержащая ответ AJAX, поэтому вы не можете использовать ее как routeValues
значение параметра внутри @Url.Action()
помощника, который содержит код на стороне сервера, поскольку сценарий еще не выполнен во время действияURL сгенерирован, а переменная response
еще не объявлена в коде на стороне сервера.
Чтобы устранить проблему, попробуйте использовать простую строку запроса для вставки EventId
параметра:
$.ajax({
url: "/Events/DeleteEvent",
data: data,
async: true,
success: function (response) {
if (response !== "" || response != "Event not found!") {
swal("Deleted!", "The event has been deleted.", "success");
// use query string because Url.Action helper runs server-side
window.location.href = '@Url.Action("Index", "Events")' + '?EventId=' + response;
} else if (response == "Event not found") {
swal("Cancelled!!!", "Error : " + response, "error");
}
}
});
Или используйте заполнитель со стороны сервера, а затем измените значение параметра на response
сreplace()
:
$.ajax({
url: "/Events/DeleteEvent",
data: data,
async: true,
success: function (response) {
if (response !== "" || response != "Event not found!") {
swal("Deleted!", "The event has been deleted.", "success");
// the URL generated server-side with placeholder
var targetUrl = '@Url.Action("Index", "Events", new { EventId = "xxx" })';
// replace placeholder with event ID
window.location.href = targetUrl.replace("xxx", response);
} else if (response == "Event not found") {
swal("Cancelled!!!", "Error : " + response, "error");
}
}
});
Дополнительное примечание:
Лучше использовать свойство на стороне клиента в ответе, чтобы различать условия успеха и ошибки, как показано в примерениже:
if (eventid > 0)
{
...
return Json(new { id = id });
}
else
return Json(new { message = "Event not found" });
AJAX-вызов
$.ajax({
url: '@Url.Action("DeleteEvent", "Events")',
data: data,
async: true,
success: function (response) {
if (typeof response.id !== 'undefined' && response.id != null) {
swal("Deleted!", "The event has been deleted.", "success");
// use query string because Url.Action helper runs server-side
window.location.href = '@Url.Action("Index", "Events")' + '?EventId=' + response.id;
} else if (typeof response.message !== 'undefined' && response.message != null) {
swal("Cancelled!!!", "Error : " + response.message, "error");
}
}
});