To show JSON returned error message - javascript

I needs to show the Json returned message.
In the controller, an exception is thrown and caught in a catch block. I am returning the fault error message.
In Ajax, the success part always executes. But if it is an error from my webservice, I don't want to execute the normal; instead I want to show an error message.
How I can achieve this?
My code below:
Controller
[HttpPost]
public JsonResult DeleteClientRecord()
{
bool result = true;
try
{
result = ClientCRUDCollection.DeleteClient(deleteClientId);
}
catch (Exception ex)
{
return Json(ex.Message, JsonRequestBehavior.AllowGet);
}
return Json(new { result }, JsonRequestBehavior.AllowGet);
}
AJAX Call
$("#YesDelete").click(function () {
$.ajax({
type: "POST",
async: false,
url: "/Client/DeleteClientRecord",
dataType: "json",
error: function (request) {
alert(request.responseText);
event.preventDefault();
},
success: function (result) {
// if error from webservice I want to differentiate here somehow
$("#Update_" + id).parents("tr").remove();
$('#myClientDeleteContainer').dialog('close');
return false;
}
});
});
Please can anyone help me on this.

[HttpPost]
public JsonResult DeleteClientRecord()
{
bool result = true;
try
{
result = ClientCRUDCollection.DeleteClient(deleteClientId);
}
catch (Exception ex)
{
return Json(new { Success="False", responseText=ex.Message});
}
return Json(new { result }, JsonRequestBehavior.AllowGet);
}

to show error message, you should add error scope after success scope in AJAX call like this:
$("#YesDelete").click(function () {
$.ajax({
type: "POST",
async: false,
url: "/Client/DeleteClientRecord",
dataType: "json",
error: function (request) {
alert(request.responseText);
event.preventDefault();
},
success: function (result) {
// if error from webservice I want to differentiate here somehow
$("#Update_" + id).parents("tr").remove();
$('#myClientDeleteContainer').dialog('close');
return false;
}
error: function (xhr) {alert(JSON.parse(xhr.responseText).Message); }
});
});

add Response.StatusCode to the response
_httpContextAccessor.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;

Related

How to get data from C# Webmethod via AJAX statuscode?

I am developing a code to check whether a data already exist on the server or not. If there is a conflict, then the program must return status code 409. I can get the data returned by the webmethod via ajax.success. However, I cannot get the data via ajax.statusCode. It always returns error:
TypeError: data is undefined
I have tried this but I got an error
Non-invocable member "Content" cannot be used like a method
How do I get my object via ajax.statusCode?
C#:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Case CreateNewCase(int id)
{
try
{
Case caseResponse = new Case();
//some process about checking if the ID exists and loading other data
if(idCount > 0)
{
HttpContext.Current.Response.StatusCode = 409;
return caseResponse;
}
else
{
HttpContext.Current.Response.StatusCode = 200;
return caseResponse;
}
}
catch (Exception ex)
{
HttpContext.Current.Response.StatusCode = 500;
return null;
}
}
JS:
function newCase() {
$.ajax({
url: 'Default.aspx/CreateNewCase',
data: JSON.stringify(
{id: ID }
),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
statusCode: {
409: function (data, response) {
//how do I get the "data" from WebMethod here?
loadCase(ID, data);
//TypeError: data is undefined
}
},
success: function (data, status) {
loadCase(ID, data);
},
error: function (data) {
}
});
}
You can do like this. Use Web API instead of Web method and return HttpResponseMessage instead of case
public HttpResponseMessage CreateNewCase(int id)
{
try
{
Case caseResponse = new Case();
//some process about checking if the ID exists and loading other data
if(idCount > 0)
{
return Request.CreateResponse( HttpStatusCode.Conflict, caseResponse );
}
else
{
return Request.CreateResponse( HttpStatusCode.OK, caseResponse );
}
}
catch (Exception ex)
{
return Request.CreateResponse( HttpStatusCode.InternalServerError, null);
}
}
If you want to use the web method approach then change the ajax and try to parse the error in errro function as given below
function newCase() {
$.ajax({
url: 'Default.aspx/CreateNewCase',
data: JSON.stringify(
{id: ID }
),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data, status) {
loadCase(ID, data);
},
error: function (jqXHR, textStatus, thrownError) {
if(jqXHR.status =="409" ){
var data= jqXHR.responseJSON;
loadCase(ID, data);
}
else
{
console.log(textStatus);
}
}
});
}

Pass table input to controller

I'm new to programming and I want to pass a table input value to the controller. I tried this:
$("#btnsend").click(function () {
$.ajax({
type: "POST",
contentType: "application/json ; charset=utf-8",
data: {
buyerID: $('.BuyerID').val(),
},
url: "/SaveReservation",
success: function (data) {
alert('buyerID : ' + data);
},
error: function (result) {
alert('something went wrong');
}
})
});
The controller is like this :
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult SaveReservation(BuyerModel buyer)
{
return Json(buyer.DistibutorID);
}
When I click the button I get a success state but in the alert I get all the source code of the project after the word buyerID.
You may want to try this:
return Json(new { success = true, message = buyer.DistibutorID },
JsonRequestBehavior.AllowGet);
And:
alert('buyerID : ' + data.message );
Notice that this here in your script
data: {
buyerID: $('.BuyerID').val(),
},
Either must have the same structure as your BuyerModel Here
public JsonResult SaveReservation(BuyerModel buyer) <- BuyerModel that you are using
{
return Json(buyer.DistibutorID);
}
Or you can Just Change your Controller to accept only one argument Like this
public JsonResult SaveReservation(string buyerID) <- Follow the same Object structure you are passing in Ajax
{
return Json(buyer.DistibutorID);
}

Ajax call showing error cant debug

this is how the javascript looks like
<script type="text/javascript">
$(document).ready(function () {
$('#loginButton').click(function () {
//this.disabled = true;
debugger;
var data = {
"userid": $("#username").val(),
"password": $("#password").val()
};
$.ajax({
url: "/Account/LoginPost",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
},
error: function () {
alert('Login Fail!!!');
}
});
});
});
I am getting the alert('Login fail') also debugger not getting hit.
I am using jquery 1.9.1 and have included unobstrusive
my controller is this as you can i am passing string values not object values
to the controller so stringify is justified here
[HttpPost]
public JsonResult LoginPost(string userid, string password)
{
using (someentities wk = new someentities())
{
var LoginUser = wk.tblUsers.Where(a => a.Username.Equals(userid)&&a.Password.Equals(password)).FirstOrDefault();
if (LoginUser != null)
{
FormsAuthentication.SetAuthCookie(userid,false);
Session["Username"] = LoginUser.Username;
Session["Password"] = LoginUser.Password;
Session["Name"] = LoginUser.Name;
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Login"] = "Please Enter Correct Login Details";
return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
}
}
// If we got this far, something failed, redisplay form
}
when page is loading these error are shown
$(..) live is not a valid function in
(anonymous function) # jquery.unobtrusive-ajax.js:115
(anonymous function) # jquery.unobtrusive-ajax.js:163
take a look to the success function
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
}
you are using multiple ", combine it with the single one ', this is a syntax error, try to check the code on an editor such as Atom, to avoid this kind of errors
Stringify converts an object to a string. Have you tried passing data an object instead of a string? Try replacing JSON.stringify(data), with data?

Redirect to View from AJAX call on error

Problem:
I would like to load a partialview into a DIV when success, but in case an error happened I need to redirect to the view home page. The issue is that the Redirect to Action is also loaded into the div resultdisplay.
How should I manage the errorhandling to Redirect to fullviews in case of error?
Code:
Ajax call:
function GetFilteredValuesCallback(values) {
var data = JSON.stringify(values);
var url = '/Controller/Action';
$.ajax({
type: 'GET',
url: url,
data: { filter: data },
success: function (result) {
$('#resultDisplay').html(result);
}
});
}
Action:
public ActionResult Action(string filter)
{
MyModel model = null;
try
{
// Do stuff with my model ...
throw new Exception("ERROR!");
}
catch (Exception ex)
{
// In case of error redirect to home page
return RedirectToAction("Index");
}
return PartialView("_PartialView", model);
}
Well instead of redirecting in controller you can just send information back to client ajax request and handle redirection here as below:
function GetFilteredValuesCallback(values) {
var data = JSON.stringify(values);
var url = '/Controller/Action';
$.ajax({
type: 'GET',
url: url,
data: { filter: data },
success: function (result) {
if(result.message==="Failed")
location.href = "yoururl"
else
$('#resultDisplay').html(result);
},
error:function(result)
{
//handle any errors
}
});
}
Controller
public ActionResult Action(string filter)
{
MyModel model = null;
try
{
// Do stuff with my model ...
throw new Exception("ERROR!");
}
catch (Exception ex)
{
// In case of error
return Json(new{message="Failed"}, JsonRequestBehavior.AllowGet); //Send a message back
}
return PartialView("_PartialView", model);
}
UPDATE
Thanks #StephenMuecke for the suggestion to handle this in more elegant way which can be done as below:
JS
function GetFilteredValuesCallback(values) {
var data = JSON.stringify(values);
var url = '/Controller/Action';
$.ajax({
type: 'GET',
url: url,
data: { filter: data },
success: function (result) {
$('#resultDisplay').html(result);
},
error:function(result)
{
location.href("yoururl");
}
});
}
Controller
public ActionResult Action(string filter)
{
MyModel model = null;
try
{
// Do stuff with my model ...
throw new Exception("ERROR!");
}
catch (Exception ex)
{
// In case of error
return new HttpStatusCodeResult(500);
}
return PartialView("_PartialView", model);
}

How to call error function in $.ajax with c# MVC4?

I have a project in MVC4 with C#. In this project, one of my controllers has a method to be called by an Ajax function:
[HttpPost]
public string EditPackage(int id, string newPkgName)
{
try{
//do logic here
return "OK";
}catch(Exception exc){
return "An error occurred, please try later! " + exc.Message;
}
}
This method is called by the following Ajax functions, using jQuery:
$.ajax({
url: $(this).data('url'),
type: 'POST',
contentType: 'application/json; charset=utf-8',
traditional: true,
data: JSON.stringify({ id: id, newPkgName: newPkgName}),
success: function () {
location.reload(true);
successNotification("Package edited successfuly!");
},
error: function (message) {
errorNotification(message);
}
});
The problem with this code, is that even if the server returns the return "An error occurred, please try later! " + exc.Message; message in the catch, the success function is the one always called.
In order words, I never run the error function no matter what I do.
To fix this I checked the official documentation:
http://api.jquery.com/jQuery.ajax/
However, since I am failry new to this I can't understand any of the parameters, nor how to use them effectively.
How can I create a good error message with all the possible information using Ajax, jQuery and my controller?
The error part of the $.ajax call only fires if the returned status code is anything other than 200 OK. In your case you are returning a plaintext response which will therefore be 200. You can change this behaviour like this:
try {
// do logic here
return "OK";
}
catch (Exception exc) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Bad Request");
}
error: function (jqXHR, textStatus, errorThrown) {
errorNotification(textStatus);
}
You can change the HttpStatusCode to whatever suits your need.
Alternatively, you can keep the 200 response and return JSON with a flag to indicate whether or not the request was successful:
[HttpPost]
public ActionResult EditPackage(int id, string newPkgName)
{
try {
//do logic here
return Json(new { Success = true, Message = "OK"});
}
catch (Exception exc) {
return Json(new { Success = false, Message = "An error occurred, please try later! " + exc.Message });
}
}
Then you can remove the error handler, and check the state of the flag in your success handler:
success: function(response) {
if (response.Success) {
location.reload(true);
successNotification("Package edited successfuly!");
}
else {
errorNotification(response.Message);
}
},
I do the following, it might not be the best approach but it works for what I try to do.
[HttpPost]
public ActionResult EditPackage(int id, string newPkgName)
{
try{
//do logic here
return Json(new {Success = true, Message = "OK"});
}catch(Exception exc){
return Json(new {Success = false, Message = "An error occurred, please try later! " + exc.Message});
}
}
Then my Ajax looks as follows:
$.ajax({
url: $(this).data('url'),
type: 'POST',
contentType: 'application/json; charset=utf-8',
traditional: true,
data: JSON.stringify({ id: id, newPkgName: newPkgName}),
success: function (data) {
if(data.Success)
{
location.reload(true);
successNotification("Package edited successfuly!");
}
else
{
errorNotification(data.Message);
}
},
error: function (message) {
errorNotification(message);
}
});
I do this so that you have the standard error catching http errors from the server, but it means you can pass a success or failure back in a way that is more useful. It also means that if your update fails for a validation reason or something you can pass that message back nicely.

Categories