【问题标题】:Return Error and view in ajax返回错误并在ajax中查看
【发布时间】:2015-05-26 07:54:19
【问题描述】:

大家好,我想知道一些事情是有可能的。如果发生其他发送视图,则使用 ajax 发送错误消息。你可以看到我的代码。请帮助我该怎么办。需要一些建议

这是我的例子

public ActionResult Test()
{
  string ErrorText = string.Empty;
  if(true)
    return View("PagedList");
  }
  else
  {
    return Json(new { errorMessage = ErrorText});
  }
}

阿贾克斯:-

function Load(page) {

            $.ajax({
                type: "POST",
                url: page,
                xhrFields: {
                    withCredentials: true
                },
                success: function (data) {

                        $('#ReportLoad').empty();
                        $('#ReportLoad').append($.parseHTML(data));

                },
                 error: function (xhr, textStatus, exceptionThrown) {
                    $('#ReportErrors').empty();
                    $('#ReportErrors').html(JSON.parse(xhr.responseText));
                    $('#ReportErrors').show();
                },
                complete: function () {
                }
            });
        }

我不知道我的做法是否正确 任何人都可以建议实现这一目标的最佳方法。

【问题讨论】:

  • 你必须在你的 ajax 请求中捕获返回
  • 你的ajax代码在哪里??
  • 如果返回错误,你应该返回 HTTP 代码 500
  • 你能给我一些样品吗#Cuong Le

标签: jquery ajax asp.net-mvc controller


【解决方案1】:

将错误代码返回为HttpStatusCodeResult,如果您只是发送回复,除非您检查响应中的特定文本,否则 Ajax 无法知道这是错误。

 public ActionResult Test()
 {
      string ErrorText = string.Empty;
      if(true)
        return View("PagedList");
      }
      else
      {
        return new HttpStatusCodeResult(500, ErrorText);
      }
 }

然后用 Ajax 检测这个:

function Load(page) {
            $.ajax({
                type: "POST",
                url: page,
                xhrFields: {
                    withCredentials: true
                },
                success: function (data) {

                        $('#ReportLoad').empty();
                        $('#ReportLoad').append($.parseHTML(data));

                },
                 error: function (xhr, textStatus, exceptionThrown) {
                    $('#ReportErrors').empty();
                    $('#ReportErrors').html(JSON.parse(xhr.responseText));
                    $('#ReportErrors').show();
                },
                complete: function () {
                },
                   statusCode: {
                   500: function(response)
                   {
                       alert("internal error");
                   }
                 }
            });
        }

【讨论】:

  • 正在显示什么?您是否尝试过使用 FireBug 或 Chrome 调试响应以查看实际响应是什么?
  • 这一行的问题实际上我删除了这行它的工作并使用警报它的工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 1970-01-01
  • 2017-12-04
  • 2012-09-07
相关资源
最近更新 更多