MVC OutputCache JsonResult returns html - ajax

I have the following controller:
[HttpPost]
[OutputCache(Duration=3600, VaryByParam="*", Location=OutputCacheLocation.Server)]
public JsonResult FreeTextQuery(SearchFiltersQuery filters)
{
Trace.TraceInformation("Entering method SearchController.FreeTextQuery");
SearchResults aResults = new SearchResults();
if (ModelState.IsValid)
{
try
{
ClaimsPrincipal user = User as ClaimsPrincipal;
aResults = _objectRepository.GetFullTextResults(filters, user);
}
catch (Exception ex)
{
if (!(#Url == null))
{
return Json(new { redirectUrl = #Url.Action("ShowError", "Error", new { message = ex.Message }), isRedirect = true });
}
}
}
Trace.TraceInformation("Exiting method SearchController.FreeTextQuery");
return Json(aResults);
}
which is called by the following ajax function
function GetResults(aFilters) {
var aEndPointUrl = "/Search/FreeTextQuery";
var jSonString = JSON.stringify(aFilters);
$.ajax({
type: 'POST',
url: aEndPointUrl,
traditional: true,
contentType: 'application/json; charset=utf-8',
data: jSonString,
success: function (data) {
// omitted for brevity
},
error: function (xhr, ajaxOptions, error) {
window.location.href = "/Error/ShowError?message=" + encodeURIComponent("Onbekende fout bij het zoeken.");
}
});
This code works fine without the OutputCache attribute on the controller. With it it always hits the error function of the ajax call and I see that the response is not JSON but HTML content (error is a parser error therefore).
What could be going wrong with the outputcaching and how do I get it working correctly? I've tried many ways of supplying VaryByParams but they all have the same result.

This post revealed the answer. The problem was outputting the trace to the page: page outputcache not working with trace

Related

Ajax post method returns undefined in .net mvc

I have this ajax post method in my code that returns undefined. I think its because I have not passed in any data, any help will be appreciated.
I have tried passing the url string using the #Url.Action Helper and passing data in as a parameter in the success parameter in the ajax method.
//jquery ajax post method
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action("Bookings/SaveBooking")',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
//controller action
[HttpPost]
public JsonResult SaveBooking(Booking b)
{
var status = false;
using (ApplicationDbContext db = new ApplicationDbContext())
{
if (b.ID > 0)
{
//update the event
var v = db.Bookings.Where(a => a.ID == a.ID);
if (v != null)
{
v.SingleOrDefault().Subject = b.Subject;
v.SingleOrDefault().StartDate = b.StartDate;
v.SingleOrDefault().EndDate = b.EndDate;
v.SingleOrDefault().Description = b.Description;
v.SingleOrDefault().IsFullDay = b.IsFullDay;
v.SingleOrDefault().ThemeColor = b.ThemeColor;
}
else
{
db.Bookings.Add(b);
}
db.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status } };
}
Before the ajax call, you should collect the data in object like,
var requestData= {
ModelField1: 'pass the value here',
ModelField2: 'pass the value here')
};
Please note, I have only added two fields but as per your class declaration, you can include all your fields.
it should be like :
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action(Bookings,SaveBooking)',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
Try adding contentType:'Application/json', to your ajax and simply have:
return Json(status);
In your controller instead of JsonResult. As well as this, You will need to pass the data in the ajax code as a stringified Json such as:
data:JSON.stringify(data),
Also, is there nay reason in particular why it's a JsonResult method?

Not getting Json object (having a collection) correctly in controller using ajax call

I am sending a json object to controller via ajax call, data property of ajax call showing correct data. On post to controller's method -received parameter having collection and its count is showing perfectly but the properties inside the collection is not showing values.
Here is the code -
Controller-
[HttpPost]
public ActionResult ImageOperations(ImageProcessingModel imageProcessingModel)
{
return Json("sucess");
}
Model-
public class ImageProcessingModel
{
public string Source { get; set; }
private List<ThumbnailImageSubTaskModel> _thumbnailImageSubTaskModel;
public List<ThumbnailImageSubTaskModel> ThumbnailImageSubTaskModel
{
get
{
if (_thumbnailImageSubTaskModel == null)
{
_thumbnailImageSubTaskModel = new List<ThumbnailImageSubTaskModel>();
}
return _thumbnailImageSubTaskModel;
}
}
}
js-
var ImageProcessingModel =
{
"Source": "test",
"ThumbnailImageSubTaskModel":allThumbnails.allItems()
}
allThumnails.allItems is ko.observableArray() which having values.
$.ajax({
url: '/ImageProcessingTask/ImageOperations',
type: 'Post',
data: ImageProcessingModel,
success: function (data, status) {
processEscapeKeyPress = true;
var fn = window[successCallback];
fn(data, passDataToCallback);
},
error: function (xhr, desc, err) {
alert(err);
processEscapeKeyPress = true;
processAjaxError(xhr, desc, err);
},
});
here ImageProcessingModel having all values and source is simple a string so this value is coming in the controller only the ThumbnailImageSubTaskModel showing counts but not its value.
Thanks!!
A common problem encoutered with sending JSON through AJAX to MVC. Many forget to set the type of data in their AJAX request.
Try setting the datatype and contentType:
$.ajax({
url: '/ImageProcessingTask/ImageOperations',
type: 'Post',
**contentType: 'application/json; charset=UTF-8',
dataType: 'json',**
data: ImageProcessingModel,
success: function (data, status) {
processEscapeKeyPress = true;
var fn = window[successCallback];
fn(data, passDataToCallback);
},
error: function (xhr, desc, err) {
alert(err);
processEscapeKeyPress = true;
processAjaxError(xhr, desc, err);
},
});

Pass ViewModel + Parameter to action using ajax call

How do I pass a view model and another parameter to my action method using jquery ajax?
with what I'm doing now, the action method is not being called. I think the cause is probably because the parameters are not being passed correctly in the data object of the jquery ajax call:
jQuery ajax:
$('#form-login').submit(function (event) {
event.preventDefault();
$.ajax({
url: "/Account/LogOn/",
data: $('#form-login').serialize(),
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.userAuthenticated) {
window.location.href = data.url;
} else {
formBlock.clearMessages();
displayError($('#errorcred').val());
}
},
error: function () {
formBlock.clearMessages();
displayError($('#errorserver').val());
}
});
});
Action method (which accepts the view model and another parameter):
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
// Validate the email and password
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
if (Request.IsAjaxRequest())
{
return Json(new { userAuthenticated = true, url = returnUrl, isRedirect = true });
}
else
{
return Redirect(returnUrl);
}
}
else
{
if (Request.IsAjaxRequest())
{
return Json(new { userAuthenticated = true, url = Url.Action("Index", "Home"), isRedirect = true });
}
else
{
return RedirectToAction("Index", "Home");
}
}
}
}
else
{
if (Request.IsAjaxRequest())
{
return Json(new { userAuthenticated = false, url = Url.Action("LogOn", "Account") });
}
else
{
ModelState.AddModelError("", adm.ErrorUserNamePassword);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Remove the following from the $.ajax call:
contentType: 'application/json; charset=utf-8',
You have specified application/json encoding but the $('#form-login').serialize() function is sending application/x-www-form-urlencoded content.
As far as sending the returnUrl parameter is concerned, you could simply read it from the form action where it should be present (if you used the Html.BeginForm() helper):
$.ajax({
url: this.action,
...
});
Also you probably want to rename the event variable with something else as this is a reserved word in javascript:
$('#form-login').submit(function (e) {
e.preventDefault();
...
});
The only way I have found to do this is to just include the second parameter in your viewmodel and continue to serialize your form the way you are doing now.

MVC3 ajax action request: handling answer

I'm doing an Ajax request to an MVC3 action and I want to process the JsonResult in the success or error function.
Currently the behaviour is strange: Before hitting my breakpoint in the action it hits the error function.
Can anyone help me please and has a hint?
My view:
<form id="myForm">
//fields go here...
<button id="myButton" onclick="myFunction();">ButtonName</button>
</form>
The ajax call:
function myFunction() {
if ($('#myForm').valid() == false) {
return;
}
var data = {
val1: $("#val1").val(),
val2: $("#val2").val()
};
var url = "/Controller/Action";
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
cache: false,
data: data,
success: function (data, statusCode, xhr) {
alert('1');
if (data && data.Message) {
alert(data.Message);
alert('2');
}
alert('3');
},
error: function (xhr, errorType, exception) {
alert('4');
var errorMessage = exception || xhr.statusText;
alert("There was an error: " + errorMessage);
}
});
return false;
}
My action:
[HttpPost]
public ActionResult Action(Class objectName)
{
var response = new AjaxResponseViewModel();
try
{
var success = DoSomething(objectName);
if (success)
{
response.Success = true;
response.Message = "Successful!";
}
else
{
response.Message = "Error!";
}
}
catch (Exception exception)
{
response.Success = false;
response.Message = exception.Message;
}
return Json(response);
}
If you look in the ajax call I get directly the alert #4 and only then the action gets called which is too late. Unfortunately the exception is null. Directly after that the view gets closed.
You are not preventing the default onclick behavior. Can you try the following instead?
onclick="return myFunction()"

Can I return custom error from JsonResult to jQuery ajax error method?

How can I pass custom error information from an ASP.NET MVC3 JsonResult method to the error (or success or complete, if need be) function of jQuery.ajax()? Ideally I'd like to be able to:
Still throw the error on the server (this is used for logging)
Retrieve custom information about the error on the client
Here is a basic version of my code:
Controller JsonResult method
public JsonResult DoStuff(string argString)
{
string errorInfo = "";
try
{
DoOtherStuff(argString);
}
catch(Exception e)
{
errorInfo = "Failed to call DoOtherStuff()";
//Edit HTTP Response here to include 'errorInfo' ?
throw e;
}
return Json(true);
}
JavaScript
$.ajax({
type: "POST",
url: "../MyController/DoStuff",
data: {argString: "arg string"},
dataType: "json",
traditional: true,
success: function(data, statusCode, xhr){
if (data === true)
//Success handling
else
//Error handling here? But error still needs to be thrown on server...
},
error: function(xhr, errorType, exception) {
//Here 'exception' is 'Internal Server Error'
//Haven't had luck editing the Response on the server to pass something here
}
});
Things I've tried (that didn't work out):
Returning error info from catch block
This works, but the exception can't be thrown
Editing HTTP response in catch block
Then inspected xhr in the jQuery error handler
xhr.getResponseHeader(), etc. contained the default ASP.NET error page, but none of my information
I think this may be possible, but I just did it wrong?
You could write a custom error filter:
public class JsonExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.ExceptionHandled = true;
filterContext.Result = new JsonResult
{
Data = new
{
// obviously here you could include whatever information you want about the exception
// for example if you have some custom exceptions you could test
// the type of the actual exception and extract additional data
// For the sake of simplicity let's suppose that we want to
// send only the exception message to the client
errorMessage = filterContext.Exception.Message
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
}
and then register it either as a global filter or only apply to particular controllers/actions that you intend to invoke with AJAX.
And on the client:
$.ajax({
type: "POST",
url: "#Url.Action("DoStuff", "My")",
data: { argString: "arg string" },
dataType: "json",
traditional: true,
success: function(data) {
//Success handling
},
error: function(xhr) {
try {
// a try/catch is recommended as the error handler
// could occur in many events and there might not be
// a JSON response from the server
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch(e) {
alert('something bad happened');
}
}
});
Obviously you could be quickly bored to write repetitive error handling code for each AJAX request so it would be better to write it once for all AJAX requests on your page:
$(document).ajaxError(function (evt, xhr) {
try {
var json = $.parseJSON(xhr.responseText);
alert(json.errorMessage);
} catch (e) {
alert('something bad happened');
}
});
and then:
$.ajax({
type: "POST",
url: "#Url.Action("DoStuff", "My")",
data: { argString: "arg string" },
dataType: "json",
traditional: true,
success: function(data) {
//Success handling
}
});
Another possibility is to adapt a global exception handler I presented so that inside the ErrorController you check if it was an AJAX request and simply return the exception details as JSON.
The advice above wouldn't work on IIS for remote clients. They will receive a standard error page like 500.htm instead of a response with a message.
You have to use customError mode in web.config, or add
<system.webServer>
<httpErrors existingResponse="PassThrough" />
</system.webServer>
or
"You can also go into IIS manager --> Error Pages then click on the
right on "Edit feature settings..." And set the option to "Detailed
errors" then it will be your application that process the error and
not IIS."
you can return JsonResult with error and track the status at javascript side to show error message :
JsonResult jsonOutput = null;
try
{
// do Stuff
}
catch
{
jsonOutput = Json(
new
{
reply = new
{
status = "Failed",
message = "Custom message "
}
});
}
return jsonOutput ;
My MVC project wasn't returning any error message (custom or otherwise).
I found that this worked well for me:
$.ajax({
url: '/SomePath/Create',
data: JSON.stringify(salesmain),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
alert("start JSON");
if (result.Success == "1") {
window.location.href = "/SomePath/index";
}
else {
alert(result.ex);
}
alert("end JSON");
},
error: function (xhr) {
alert(xhr.responseText);
}
//error: AjaxFailed
});
Showing the xhr.responseText resulted in a very detailed HTML formatted alert message.
If for some reason you can't send a server error. Here's an option that you can do.
server side
var items = Newtonsoft.Json.JsonConvert.DeserializeObject<SubCat>(data); // Returning a parse object or complete object
if (!String.IsNullOrEmpty(items.OldName))
{
DataTable update = Access.update_SubCategories_ByBrand_andCategory_andLikeSubCategories_BY_PRODUCTNAME(items.OldName, items.Name, items.Description);
if(update.Rows.Count > 0)
{
List<errors> errors_ = new List<errors>();
errors_.Add(new errors(update.Rows[0]["ErrorMessage"].ToString(), "Duplicate Field", true));
return Newtonsoft.Json.JsonConvert.SerializeObject(errors_[0]); // returning a stringify object which equals a string | noncomplete object
}
}
return items;
client side
$.ajax({
method: 'POST',
url: `legacy.aspx/${place}`,
contentType: 'application/json',
data: JSON.stringify({data_}),
headers: {
'Accept': 'application/json, text/plain, *',
'Content-type': 'application/json',
'dataType': 'json'
},
success: function (data) {
if (typeof data.d === 'object') { //If data returns an object then its a success
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
})
Toast.fire({
type: 'success',
title: 'Information Saved Successfully'
})
editChange(place, data.d, data_);
} else { // If data returns a stringify object or string then it failed and run error
var myData = JSON.parse(data.d);
Swal.fire({
type: 'error',
title: 'Oops...',
text: 'Something went wrong!',
footer: `<a href='javascript:showError("${myData.errorMessage}", "${myData.type}", ${data_})'>Why do I have this issue?</a>`
})
}
},
error: function (error) { console.log("FAIL....================="); }
});

Resources