Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to be able to return json object with a custom error/success message using the same line of code: i have these two lines of code:

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


I want to be able display it in one line like this:

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


I will appreciate any assistance from anyone

What I have tried:

My Server side Code:

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



My Ajax Function:

<script type="text/javascript">

            $.ajax({
                url: '/Appointment/InsertPatientAppointment/',
                type: "POST",
                data: JSON.stringify({ appointmentDate: $(".datetimepicker").val() }),

                cache: false,
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (_data) {
                    if (_data.f !== undefined) {
                        swal({
                            title: "Failed!",
                            text: _data.f,
                            type: "info"
                        });
                        table.clear().draw();
                        return false;
                    }
                    else {
                        swal({
                            title: "Success!",
                            text: _data.s,
                            type: "success"
                        });

                    }
                }
            });
        });
    });

</script>
Posted
Updated 15-Nov-18 23:58pm
Comments
F-ES Sitecore 12-Nov-18 10:50am    
Your code makes no sense, "return" stops the code execution so the code after it won't ever run.
Uwakpeter 13-Nov-18 3:31am    
yes i know sir, that can't work, the point i was trying to make was that i wanted to be able to display both in one line of code.

You can't have multiple return statements in your code. If you want to return the data with message, then you have to create a custom object that combines and wrap both your data and custom message and return that object instead. For example you could create a custom object like this:

C#
public class MyCustomResponse
{
    public object Data { get; set; }
    public string Message { get; set; }
}


Then in your Controller, you can return that object like this:

C#
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getList); 
var response = new MyCustomResponse(){
	Data = data,
	Message = "Successful"
};

return Json(response);


You may want to give this article a read too:
ASP.NET Core and Web API: A Custom Wrapper for Managing Exceptions and Consistent Responses[^]
 
Share this answer
 
Comments
Uwakpeter 12-Nov-18 11:36am    
How do i use this in the ajax function?
Vincent Maverick Durano 12-Nov-18 15:43pm    
You can still use your existing AJAX code, except that the data is available via:

_data.f.Data and _data.f.Message
There are two different methods that I use for delivering the data as well as a "status" message. The choice on the method to use is all based on a case by case basis.

The easiset method would be to utilize a "composite" object; wrapping the data and the status into a new object. You could also use incorporate a class for this. The downside to this method is it will require another step in parsing the actual JSON you want
return Json(new { ReturnStatus = "error", ReturnData = data });

The second method would be a little more complicated, and that would be to leverage the response object either using custom headers or status messages. The downside to this is that your AJAX functions will need to be expanded to pull the information out.
AJAX XMLHttpRequest Server Response[^]
 
Share this answer
 
Comments
Uwakpeter 12-Nov-18 11:29am    
yes this should work i have tried it before, but it tends to create another issue, record inserted does not show automatically on the datatable anymore until the page is manually refreshed, is there a way i can also make it show like before with the above line of code?
MadMyche 12-Nov-18 12:55pm    
Without the relevant code (getID, GetAppointmentList), it is hard to determine why your program isn't showing the updated info
I was able to resolve this eventually steps below:

I integrated the data object in my anonymous object which i am are already returning:
return Json(new {data = data, f = "error"});


Then access the data object in my ajax call like this:

success: function (_data) {
    var returnedData = _data.data;
}


Which means i have to adjust my map method call where i am preparing the data array for the table. Instead of:

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


Then call it with the data object _data.data:

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


This actually did the trick for me.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900