将控制器中的字符串发送到View中的Ajax [英] Sending string in controller to Ajax in View

查看:41
本文介绍了将控制器中的字符串发送到View中的Ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Ajax在控制器中调用动作,如果操作成功,它将返回FileContentResult,如果失败,则抛出异常.引发异常时,我正在发送一个字符串,我想将其显示为警报,但无法从xmlHttpRequest中提取字符串(excep).

I'm calling an action in controller using Ajax, If The action is success it will return FileContentResult, if it fails i'm throwing exception. When throwing exception i'm sending a string and i want to show it as alert, but unable to extract the string (excep) out of the xmlHttpRequest.

在控制器中引发的异常:

The Exception thrown in the controller:

if (existInProgress)
{
  excep = "Cannot create file, some orders are already in status In Progress.";
  throw new Exception(String.Format(excep));
}

Ajax调用:

$.ajax({
  url: "OrderWarehouse/Export",
  type: "POST",
  data: pdata,
  contentType: false,
  success: function (data) {
         swal("Success!", "Success!", "success").then((value) => { location.reload(); })
                },
  error: function (XMLHttpRequest, textStatus, errorThrown) {
      var respJson = XMLHttpRequest.responseText;
      var jsonexp = JSON.parse(respJson);
      window.alert(jsonexp.data);
      swal("Error!", "Error!", "error").then((value) => { location.reload(); })
   }
});

为什么无法在其中识别Parse.JSON?

Why Parse.JSON is not recognize there?

我还可以通过哪些其他方式提取文本?

what other ways can i extract the text?

谢谢!

推荐答案

这不是返回异常消息以查看的正确方法.如果将断点放在ajax调用上,则可以检查 respJson 以及为何无法对其进行解析.这不是您想要的正确格式.

It's not a right way to return exception messages to view. If you put breakpoint on your ajax call, you could inspect respJson and why it couldn't be parsed. It's not the right format that you want.

错误函数用于某些未处理的异常,例如500个,我们不知道.处理我们的异常是没有道理的.

error function is for some unhandled exception that we don't know about it like 500 ones. Handling our exceptions makes no sense.

我想您只需要返回一些JSON对象就不需要抛出异常

I guess you don't need throwing the exception just returning some JSON object is enough

return Json(new { Success = false, Message = excep });

但是抛出异常是不可避免的,您可以像下面这样:

But throwing exception is inevitable, you could do it like below:

try {
  if (existInProgress) {
    var excep = "Cannot create file, some orders are already in status In Progress.";
    throw new Exception(String.Format(excep));
  }

  return Json(new {
    Success = true,
    Status = yourModel
  });
}
catch(Exception ex) {

  return Json(new {
    Success = false,
    Message = ex.Message
  });
}

这篇关于将控制器中的字符串发送到View中的Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆