如何在发布请求时返回带有消息的json对象给ajax函数

时间:2018-11-12 15:27:41

标签: c# json ajax asp.net-mvc

我希望能够在发布请求时使用同一行代码返回带有自定义错误/成功消息的json对象:我有这两行代码:

return Json(data);
return Json(new { f = "error" });

我希望能够像这样在一行中显示它:

return Json(data, Json(new { f = "error" }));

我知道我的代码中不能包含多个return语句。但是我想返回带有消息的数据。

我的服务器端代码:

if (getId > 0)
{
    var getList = appointmentRepository.GetAppointmentList(userId);
    var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);                       
    return Json(data);
    return Json(new { s = "success" });
}
else
{
    var getList = appointmentRepository.GetAppointmentList(userId);
    var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);
    return Json(data);
    return Json(new { f = "error" });
}

我的Ajax功能:

<script type = "text/javascript">
   $(document).ready(function () {
      $('#tblAppointment').DataTable({
         dom: 'Bfrtip',
         buttons: [
            'copyHtml5',
            'excelHtml5',
            'csvHtml5',
            'pdfHtml5'
         ]
      });

      var table = $("#tblAppointment").DataTable();
      $("#saveButton").click(function () {

         console.log("appDate:" + $('.datetimepicker').val());
         $.ajax({
            url: '/Appointment/InsertPatientAppointment/',
            type: "POST",
            data: JSON.stringify({
               appointmentDate: $(".datetimepicker").val(),
               patientRegNo: $("#patientRegNo").val(),
               reasons: $("#reasons").val()
            }),

            cache: false,
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (_data) {
               if (_data.f !== undefined) {
                  swal({
                     title: "Failed!",
                     text: _data.f, //"Ooops! something went wrong, 
                     record not saved,
                     try again later ",
                     type: "info"
                  });
                  table.clear().draw();
                  //table.destroy();
                  // $("#viewReportBtn").prop("disabled", false);
                  return false;
               } else {
                  swal({
                     title: "Success!",
                     text: _data.s, //"Appointment added successfully!",
                     type: "success"
                  });

               }
               $(".datetimepicker").val('');
               $("#patientRegNo").val('');
               $("#reasons").val('');

               var arr = $.map(JSON.parse(_data), function (el) {
                  return
                  el
               });

               if (arr.length === 0) {
                  swal({
                     title: "No Record Found!",
                     text: _data.f, //"Your search returns an empty 
                     result set !",
                     type: "info"
                  });
                  table.clear().draw();
                  return false;
               }
               table.clear();
               table.destroy();
               $('#tblAppointment').dataTable({
                  data: arr,
                  columns: [{
                        "data": "MatricRegNo"
                     },
                     {
                        "data": "PatientName"
                     },
                     {
                        "data": "EntryDate"
                     },
                     {
                        "data": "AppointmentDate"
                     },
                     {
                        "data": "Reasons"
                     },
                     {
                        "data": function (data, type, row, meta) {
                           return '<span class="fa fa-edit" data- 
                           toggle = "modal"
                           data - target = "#modal-Edit" > < /span>';
                        }
                     }
                  ],
                  dom: 'Bfrtip',
                  buttons: [
                     'copy', 'csv', 'excel',
                     {
                        extend: 'pdfHtml5',
                        orientation: 'Portriat',
                        pageSize: 'A4'
                     }
                  ]
               });
               table = $("#tblAppointment").DataTable();
            }
         });
      });
   });
</script>

3 个答案:

答案 0 :(得分:1)

您可以使用此:

var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList);

var returnData = new object[2];
  returnData[0] = data;
  returnData[1] = new { f = "error" };
  return Json(returnData);

答案 1 :(得分:0)

我可能会以以下方式处理,将JsonResult扩展为包括状态码。这样,您就可以决定Ajax请求的成功级别。

public class JsonResultWithStatusCode : JsonResult
{
     private readonly HttpStatusCode statusCode;

     public JsonResultWithStatusCode(object data, HttpStatusCode statusCode)
     {
          Data = data;
          this.statusCode = statusCode;
     }

     public override void ExecuteResult(ControllerContext context)
     {
         context.RequestContext.HttpContext.Response.StatusCode = (int)statusCode;
         base.ExecuteResult(context);
     }
}

然后在您的控制器内部:

if(...) 
{
     var model = JsonConvert.SerializeObject(...);
     return new JsonResultWithStatusCode(model, HttpStatusCode.Ok)
}

else 
{
     var model = new { error = "..." };
     return new JsonResultWithStatusCode(model, HttpStatusCode.InternalServerError);
}

然后在Ajax内部,您将能够读取状态码,然后读取正文。

.success: function(response) {
     console.log(response.status); // Status Code (200 or 500 based on above)
     console.log(response.data); // Our model based on above, one writing error the other actual model data.
}

您要做的所有事情都会根据服务器的输出进行读取。

答案 2 :(得分:0)

您可以将{{ ... }}对象集成到已经返回的匿名对象中:

data

如果您这样做,则可以在ajax调用中访问数据对象,如下所示:

return Json(new {data = data, f = "error"});

这意味着您必须在准备表的数据数组的地方调整success: function (_data) { var returnedData = _data.data; } 方法调用。代替:

map

使用数据对象var arr = $.map(JSON.parse(_data), function (el) { return el }); 调用它:

_data.data

这应该可以解决问题。