Почему «ответ» не доступен в текущем контексте? - PullRequest
0 голосов
/ 13 марта 2019

У меня есть следующий фрагмент кода здесь.Я пытаюсь обновить страницу страницей /Events/Index, когда запрос Ajax выполнен успешно.Однако внутри метода success я вижу, что переменная response доступна в случае else if, но она недоступна в случае if.Внутри if корпуса я получаю ошибку: The name response does not exist in the current context.

Вызов Ajax от View выглядит следующим образом:

$.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");
        window.location.href = '@Url.Action("Index", "Events", new { EventId = response })';

    }
    else if (response == "Event not found")
        swal("Cancelled!!!", "Error : " + response, "error");
});

Так я отправляю ответ на часть success вызова Ajax изController:

if (eventid > 0)
{
    ...
    return Json(id);
}
else
    return Json("Event not found");
// id is an integer value that I want to send to success in Ajax.

Я где-нибудь ошибаюсь?

Ответы [ 3 ]

1 голос
/ 14 марта 2019

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");
      }
   }
});
1 голос
/ 13 марта 2019

Попробуйте это:

$.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");
         window.location.href = '@Url.Action("Index", "Events", new { EventId = "' + response + '" })';

      } else if (response == "Event not found") {
         swal("Cancelled!!!", "Error : " + response, "error");
      }
   }
});

В вашем синтаксисе есть ошибки.Посмотрите на код, и вы увидите разницу в синтаксисе.
Дайте мне знать, как это происходит.

0 голосов
/ 13 марта 2019

передать значение ответа вместо его имени

'@Url.Action("Index", "Events", new { EventId = "' + response + '" })'

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...