AJAX error in ASP.NET c# - c#

I am very new to Ajax and ASP.NET MVC. I have a function, that returns back to AJAX and I need to handle the error situation. When everything works fine, then the code is okay. My question is how to handle the error part. Here is what I have:
To return success I have:
var data = new { success = false };
return Json(data, JsonRequestBehavior.AllowGet);
And I need to know what to return when there is an exception or error??
This is my query:
function DoMailPDF() {
$("#submitMail").attr("disabled", true);
var personid = $("#personid").val();
var unitid = $("#unitid").val();
var url = "#(Url.Action("SendEmail", "Report"))";
$.ajax({
url: url,
data: { person: personid , unit:unitid},
success: function () {
// $('input[name=MailSent]').attr('checked', true);
$("#submitMail").removeAttr("disabled");
alert("Email sent!");
},
error: function () {
alert("Email not sent!");
}
});
}
It never comes to the error function. How do I make it go to the error? Any tips and suggestions are most welcome.

You can access your json response object by writing:
$.ajax({
url: url,
data: { person: personid , unit:unitid},
dataType: 'json',
success: function (response) {
if (response.success == false) {
// Error handling
} else {
// Success handling
}
},
error: function () {
alert("Email not sent!");
}
});

As Nick Bork already explained in a comment, the error/success status of a response is determined by the Http status code that is sent down in the header. You can still go the suggested way and inspect the response object and the success property but it is clearly not the proper way when you already have a more powerful and long proven mechanism (the HTTP protocol itself).
.NET will use HTTP 200 (OK) when everything goes according to the code but you can change this behaviour in the Controller by accessing the Reponse object like this, for example:
Response.StatusCode = 500; // or any of the other HTTP "failure" status codes
Any status code in the 4xx or 5xx category will trigger the error() handler specified in the $.ajax(...) call. From there you can of course also inspect the proper status code, the response details and every properties of the XHR object to provide a more meaningful user experience.
HTTP status codes are pretty much set in stone and are not likely to change, that's why they are in my opinion definitely preferrable to a custom made solution...
PS: For a list of HTTP status codes, wikipedia is your friend.

Related

Receiving a C# Enum in JavaScript and passing it to a model via Ajax

In my code, I need to receive a string, convert it into a C# enum, and pass the enum to my model. The code is within a for-loop (not shown).
var thisDwm = document.getElementById("dwm_" + i).value;
var urlDwm = "/KnowledgeTransfer/GetDailyWeeklyMonthlyEnum";
var response
$.ajax({
type: 'GET',
url: urlDwm,
data: { 'caseFromJS': thisDwm },
contentType: 'application/json',
success: function (thisResponse) {
response = thisResponse;
}
})
model.MainResponsibilities[i].DailyWeeklyMonthly = response;
Currently the ajax hits my C# controller and returns the correct enum. But when I look at the JavaScript breakpoints, "response" remains undefined and is not set. How do I set the response to a C# enum object that I can pass to my model? Is there some parsing that needs to happen? It seems like I am not receiving anything from the controller at all.
One thing that doesn't help is that type, data, contentType, success, and thisResponse all show as "having a reference error is undefined" in Chrome. Yet the Ajax still works, at least in other places, even though these other methods also show this error.
Thank you for your assistance.
Edit: below is my controller method:
public ObjectModel.Enums.DailyWeeklyMonthly GetDailyWeeklyMonthlyEnum(string caseFromJS)
{
switch (caseFromJS){
case "Daily":
return ObjectModel.Enums.DailyWeeklyMonthly.Daily;
case "Weekly":
return ObjectModel.Enums.DailyWeeklyMonthly.Weekly;
case "Monthly":
return ObjectModel.Enums.DailyWeeklyMonthly.Monthly;
case "Yearly":
return ObjectModel.Enums.DailyWeeklyMonthly.Yearly;
default:
throw new Exception("problem with dailyWeeklyMonthly in KnowledgeTransferController");
With the code you shared, you will get response is not defined error if you are trying to use the response variable before it is defined. In the code snippet you shared, you are initializing it only inside the success callback method of your ajax call.
Remember, ajax is asynchronous. When JavaScript framework executes this line model.MainResponsibilities[i].DailyWeeklyMonthly = response;, which is outside the success callback scope, The ajax call might be still executing/waiting for the response from the server, this means nothing has been set to response, which means the variable response is not initialized!
Access the response for your ajax call only inside the success or done callback.
$.ajax({
type: 'GET',
url: urlDwm,
data: { 'caseFromJS': thisDwm },
contentType: 'application/json',
success: function (thisResponse) {
// safe to use thisResponse in this callback method scope
console.log(thisResponse);
// Assuming model.MainResponsibilities[i] exist
model.MainResponsibilities[i].DailyWeeklyMonthly = thisResponse;
}
})

jquery AJAX get encountering undefined error for valid json response

Team - I am new to jquery and facing issue with a valid json response giving unknown error.
Web based C# MVC and backend database is SQL Server. I am using EF.
If I use the below code:
IQueryable dbResult = dbContext.ParentRecord.Where(row => row.Id ==id).Include(row => row.ChildRecord);
if (dbResult != null) { return Ok(dbResult) }
I have verified that the HTTP Status code is 200, the child records are populated correctly and tested the structure to be a valid json.
However the above encounters error in get function. If I remove the Include - the ParentRecord.ChildRecord is null and the get works.
There are no details available about the error in the xhr object. It enters the error function and response is undefined. (code below)
Please note: I have tried with fail function, datatype: "json",
content-type: "application/json, charset=UTF-8" combinations as well.
$.ajax({
url: _url,
cache: false,
error: function (xhr, status, error) {
alert("error : " + xhr.responseText);
}
}).done(function (data) {
alert("inside " + data);
})
Can anyone point me to the root cause of the error? Or help me get more details on the actual error?
include success for e.g:
cache: false,
success: function(reponse){
//parse your serverside code from resonse
}
I hope this works for you.
plus in javascript/jquery, execution stops at the line where it finds an error in code.
and in your ajax you have a extra 'comma' at the end. I'll Bold it.
.ajax({
url: _url,
cache: false,
error: function (xhr, status, error) {
alert("error : " + xhr.responseText);
}, // <=== there's extra comma here. When comma is mentioned it expects for another parameter as you're passing an object. Remove it.
}).done(function (data) {
alert("inside " + data);
})
The issue is traced to Fluent API in C#. Apparently what I did not realize is that jquery is not only expecting a valid json structure but also validating the json response with the respective class.
Unfortunately jquery get error did not provide me any details about the error, which made it hard to detect the anomaly (esp. for newbies like me)
The validation to class failed in this case as it was expecting a ChildRecord.ParentRecord = null field in the response structure. This anomaly is due to Fluent API navigation property definition where the ChildRecord class has the following declaration:
[ForeignKey("PID")]
public virtual ParentRecord ParentRecord { get; set; }
The work around would be to either explicitly set ChildRecord.ParentRecord as null and ensure it is passed into the response or change the Fluent API definition.
I went with the second option.

Custom client-side validation

I want to check whether a username entered is already used or whether it is available. I have used the Remote attribute from System.Web.Mvc and it is working fine. I was basically using this link for reference.
However, I wonder if the same can be implemented using a button click on the form without submitting the form.
I am asking this because I want to show an error message if the name is already used and I also want to show another message if it is available (like "Username Available").
Is there any way to do this?
I'm using MVC 4 on Visual Studio 2012.
You need to make ajax call to your controller action on button click (Jquery) and check your response on success and display your error message.
$("#btnCheckUserName").click(function () {
var userName = $('#txtUserName').text;
$.ajax({
url: 'home/IsUserNameInUse',
data: { userName: userName },
success: function (data) {
if (data.exists === true) {
//display your err message here
}
else {
//do something
}
}
});
});
Of course you need to define a controller action called IsUserNameinUse that takes a string variable userName.
Let me know if you have difficulty defining the action.
Ok I think I solved this. A huge thanks to #yohanis for helping out with the basic here. I found slight errors in the code, otherwise it worked fine.
$(document).ready(function() {
$("#btnCheckUserName").click(function() {
var userName = $('#txtUserName').val();
$.ajax({
url: 'home/IsUserNameInUse',
data: {
userName: userName
},
dataType: "json",
success: function(data) {
if (data == undefined) {
//do something
} else {
//display your err message here
}
}
});
});
});

Console Log Returning HTML Page Text Instead of JSON

I am trying to return a model in JSON form from a request sent as the following:
$(document).ready(function() {
(function(){
console.log("ran");
$.ajax({
type: "GET",
url: "https://clas.uconn.edu/Employees/Edit/22",
success: function(data) {
console.log("Success: " + data);
empData = data;
}
});
})();
});
My Controller for this method is:
// GET: Employees/Edit/5
public ActionResult Edit(int? id)
{
var id = employee.id;
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
if (employee == null)
{
return HttpNotFound();
}
return new JsonResult() { Data = employee, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
Console.WriteLine("error");
}
However I am getting an entire html page in the consol log even though none of these controller actions return a view. Any ideas?
Edit:
After adding the datatype, I am getting an error in the console log saying:
GET http://localhost:59909/Employees/EmployeeLookupDisplay
net::ERR_CONNECTION_REFUSED
It is returning the entire page because there is an error in your request somewhere.
Add a block error to your ajax call and console.log on the xhr. You will get much more information about the error like this.
What you can try is making the request on POST and checking the properties of the context on the C# code. Sometimes adding dataType and the encoding helps for the request.
Additionally check for the returning status of your request on your browser developer tools. In chrome it is the network tab that shows all requests and their status.
Try This, but according to your code its always returning HTTP not foud which is HTML page. if you have data to employee. i mean your controller action getting success without any error. then you can try tis.
$.ajax({
type: "GET",
url: "https://clas.uconn.edu/Employees/Edit/22",
dataType: "json",
success: function(data) {
console.log("Success: " + data);
empData = data;
}
Maybe instead of returning new JsonResult() { Data = employee, JsonRequestBehavior = JsonRequestBehavior.AllowGet };, just return Json(employee, JsonRequestBehavior.AllowGet);'
Another thing i see:
on the first line you are doing var id = employee.id; -> where employee comes from? maybe the error is there.

JQuery AJAX, Error Status code: 200, Status Text: parserorro | OK

Here is a funny situation that I'm in.
I'm developing an ASP.Net web site using VS 2008 and .Net Framework 3.5, and I want to use jquery ajax in a test page, the code looks like this:
C# Method
[WebMethod]
public static string test()
{
return "Server Response" ;
}
$(document).ready(function() {
$("#myDiv").click(function() {
$.ajax({
type: "POST",
url: "AjaxTest.aspx/test",
data: "",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page
// method's return.
alert(msg.d);
},
error: function(result){
alert("error occured. Status:" + result.status
+ ' --Status Text:' + result.statusText
+ " --Error Result:" + result);
}
});
});
});
So When I use Jquery 1.4.4 like this :
I get : Status 200; Status Text: OK
When I use Jquery 1.5 I get: Status 200; Status Text: Parsererror
So I created a new WebSite in Visual Studio, copy and pased the code there, and it works fine !!!! I can't figure out what causes the problem.
Also I have used methods with parameter, and setting data:"{}", and removing data completely, but nothing seems to work.
I don't know if has to do anything with the DevExpress components that I'm using or not.
I also found a good answer which was working with complete method like this :
complete: function(xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
But I don't know if it will work fine or there might be some other problem with this method too. I also don't know how to access response data from here.
But my main concern is finding out what is causing the problem in my website.
UPDATE: Well today in Google Chrome console I noticed some syntax problems with JQuery 1.5
they are as below:
Uncaught SyntaxError: Unexpected token <
jQuery.jQuery.extend.globalEvaljquery.js:593
jQuery.ajaxSetup.converters.text scriptjquery.js:7175
ajaxConvertjquery.js:7074
donejquery.js:6622
jQuery.ajaxTransport.send.callbackjquery.js:7441
The issue isn't so easily solved with fiddler, although it's a great tool.
The issue I think is described here, and for now use the complete event.
there are some issues that will be resolved in jQuery 1.5.1
See:
jQuery returning "parsererror" for ajax request
as it was posted there,
complete: function (xhr, status) {
if (status == 'error' || !xhr.responseText) {
handleError();
}
else {
var data = xhr.responseText;
//...
}
}
Although the interesting thing is - this works for me with jsonp data when I query amazon's service (code amazon was based on some other posting on the net I don't have the ref too) ala:
//resp is simple a placeholder for autocomplete's response which I will need to call on a global scope.
var resp;
var filter;
$(document).ready(function () {
//http://completion.amazon.com/search/complete?method=completion&q=halo&search-alias=videogames&mkt=1&x=updateISSCompletion&noCacheIE=1295031912518
filter = $("#productFilter").autocomplete({
source: function (request, response) {
resp = response;
$.ajax({
url: "http://completion.amazon.com/search/complete",
type: "GET",
cache: false,
dataType: "jsonp",
success: function (data) {
//data[1] contains an array of the elements returned from the service.
//use .map to enumerate through them.
response($.map(data[1], function (item) {
//debugger;
return { label: item, value: item, id: item}
}))
},
data: {
q: request.term,
"search-alias": "videogames",
mkt: "1",
callback: '?'
}
});
},
minLength: 2,
select: function (event, ui) {
//$('#browseNode option:first').attr('selected', 'selected');
alert('selected');
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
//this is the method that will be called by the jsonp request
function updateISSCompletion() {
alert('updateiss');
resp(completion[1]);
}
You should use Fiddler - the great web debugging proxy. With its help you can watch for all communication between server and client
Not sure if this will help, but the ajax() API specifies that they have changed the return object for the success() callback function. This is from the jQuery API
As of jQuery 1.5, the success callback function receives a "jqXHR" object (in jQuery 1.4, it received the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.
You can find it here if it helps at all...
jQuery $ajax API
I am running into a similar problem, and am unable to pull the JSON object from any callback functions.
I had this problem too but in PHP When i put in 'remote.php':
`echo $msg`'
problem occurs. When I use json_encode():
echo json_encode($msg);
then everything works.
This is strange, because I get response from server with status 'OK', so then function 'success' should work not 'error'. In 'success' i have only
success: function(res){ console.log(res);}
In my case (when using "jquery 1.9.1"), adding dataType: "json" solved the "parsererror" problem (I didn't specify dataType before and that problem occurred).
I had a similar problem.
I called in AJAX a REST service with POST method and got back :
arguments[0] = status 200 (OK) | arguments[1] = "parseerror" | arguments[2] = "Invalid JSON :"
My server method returned a "void" value. To resolve the problem, I replaced it by a Boolean value for example.

Categories

Resources