Sending string in controller to Ajax in View

◇◆丶佛笑我妖孽 提交于 2021-01-29 06:44:32

问题


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 call:

$.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(); })
   }
});

Why Parse.JSON is not recognize there?

what other ways can i extract the text?

Thank you!


回答1:


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.

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

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
  });
}


来源:https://stackoverflow.com/questions/65010486/sending-string-in-controller-to-ajax-in-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!