I am unable to get a json response from my controller action. The network shows as a post which is correct as I am posting a file to the server, however, needs a JSON response sent back to my view.
public JsonResult Upload(HttpPostedFileBase file, int id)
{
Homes thishomes= _db.Homes.FirstOrDefault(t => t.Id == id);
FileUploader fileupload = new FileUploader();
fileupload.PostIt(file.InputStream);
return Json(new { success = true, response = "File uploaded.", JsonRequestBehavior.AllowGet });
}
JQUERY using Dropzonejs:
Dropzone.options.DropzoneForm = {
paramName: "file",
maxFilesize: 2000,
maxFiles: 28,
dictMaxFilesExceeded: "Custom max files msg",
init: function () {
this.on("success", function () {
alert("Added file");
})
}
};
Can anyone see an this issue?
Try to write [HttpPost] attribute over your action. Also "The network shows as a post which is correct" if its post then you don't need JsonRequestBehavior.AllowGet
when you are returning Json to your request
Related
I have a form in ExtJS:
{
xtype: 'form',
items: [{
xtype: 'filefield',
name: 'azezFile'
}],
buttons: [{
text: 'Load',
handler: function() {
var form = this.up('form').getForm();
if(form.isValid()) {
form.submit({
url: uploadApiPath,
success: function(fp, o) {
// Never goes here
}
});
...
It sends file to a controller (.Net5):
namespace KROSS_Core.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Produces("application/json")]
public class UploadController : ControllerBase
{
// POST: api/Upload
[HttpPost]
public IActionResult Post([FromForm] IFormFile file)
{
//AzezUploadFile(this.HttpContext);
return Ok(new { success = true });
//return Ok(LoadFileToBase(this.HttpContext));
//return BadRequest(new { success = false, message = "Wrong answer" });
}
Controller getting request and responses normally, but I got an exception in ext-all-debug.js:
Unhandled exception at line 6092, column 17 in
https : // localhost:44364/Website/Scripts/ext.js/ext-all-debug.js
0x800a139e - Error JavaScript: Ext.JSON.decode(): You're trying to
decode an invalid JSON String:
And response.responseText is empty in debugger. After I close that exception, the browser (IE11) asks me to save or open that json file.
Firefox shows another error in console:
"You're trying to decode an invalid JSON String: <pre>{\"success\":true}</pre>"
, but it was set [Produces("application/json")] in controller...
Google Chrome log: "You're trying to decode an invalid JSON String: <pre style="word-wrap: break-word; white-space: pre-wrap;">{"success":true}</pre>"
What is the problem and how to make it working? The same controller method loaded without sending multipart form-data goes normally and ExtJS works with response JSON.
I have no idea how to fix it in ExtJS, but I used another method of uploading a file to a server (same controller), and it works perfect:
function uploadFile(file, url, success, failure) {
var formData = new FormData();
var request = new XMLHttpRequest();
formData.append('file', file);
request.onload = function (response) {
var jsonResult = JSON.parse(response.target.responseText);
if (jsonResult.exception || jsonResult.error) {
failure(jsonResult);
}
else {
success(jsonResult);
}
};
request.open("POST", url);
request.send(formData);
}
And use it like
uploadFile(form.down('[name=fileInnputName]').extractFileInput().files[0], uploadApiPath, function() { }, function() { });
I need to retrieve JSON or HTML from my MVC controller by an Ajax call.
The question is why that below doesn't work with a GET request ?
$.ajax({
url: url,
type: "POST", //It works but doesn't work with GET
success: function (data) {
...
}
});
public ActionResult Index()
{
if (User.Identity.IsAuthenticated)
{
...
return View(selectedUser);
}
return Json(new { Error = Messages.AUTHENTICATIONEXPIRED });
}
With HTTP GET it get nothing instead the Json Object.
The Action method is executed successfully.
Is there a technical reason that I don't know? is there another way to make it work without making a POST call?
Thanks
When returning Json through GET, you have to add JsonRequestBehavior.AllowGet :
return Json(new { Error = Messages.AUTHENTICATIONEXPIRED }, JsonRequestBehavior.AllowGet);
More info there.
I'm trying to post some data from a dart project to another and store them in a mongoDB
Post code:
import 'dart:io';
void main() {
List example = [
{"source": "today", "target": "tomorrow"},
{"source": "yesterday", "target": "tomorrow"},
{"source": "today", "target": "yesterday"}
];
new HttpClient().post('localhost', 4040, '')
.then((HttpClientRequest request) {
request.headers.contentType = ContentType.JSON;
request.write(example);
return request.close();
});
}
Code that receives it, inside another file
void start() {
HttpServer.bind(address, port)
.then((HttpServer server) {
// Log in console to show that server is listening
print('Server listening on ${address}:${server.port}');
server.listen((HttpRequest request) {
request.transform(UTF8.decoder).listen(sendToDatastore);
});
});
}
void sendToDatastore(String contents) {
var dbproxy = new dbProxy("myDb");
dbproxy.write("rawdata", contents);
index++;
// non related to the problem code
}
bool write(collectionName, document)
{
Db connection = connect();
DbCollection collection = connection.collection(collectionName);
connection.open().then((_){
print('writing $document to db');
collection.insert(document);
}).then((_) {
print('closing db');
connection.close();
});
return true;
}
What I'm struggling with is that I'm using
request.transform(UTF8.decoder).listen(sendToDatastore);
so I'm converting the request stream to a string as I couldn't find the way to send it as Json.
And then in sendToDatastore I'm not able to parse it properly in order to store it. As far as I understand I'd need to get every Json object as a Map to store it as I'm getting this error
Uncaught Error: type 'String' is not a subtype of type 'Map' of 'document'.
Thanks,
UPDATE
If I try to do something like this in sendToDatastore
void sendToDatastore(String contents) {
var dbproxy = new dbProxy("myDb");
var contentToPass = JSON.decode(contents);
contentToPass.forEach((element) => dbproxy.write("rawdata", element));
index++;
// non related to the problem code
}
It raises this error
Uncaught Error: FormatException: Unexpected character (at character 3)
[{source: today, target: tomorrow}, {source: yesterday, target: tomorrow}, ...
^
In the use of JSON.decode
UPDATE2
The error was that I wasn't sending actual Json from the "post code". I used
// ...
request.write(JSON.encode(example));
// ...
and everything worked fine
Thanks
You should be able to use the dart:convert package.
You can then use:
String str = JSON.encode(obj)
and
var obj = JSON.decode(str)
to convert string/json.
This is weird issue I have so far.
I am using jaxon backbone to do this Angularjs project.
java resource file
#GET #Path("{query}")
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Signature findByName(#PathParam("query") String query) {
return dao.findById(query);
}
control.js file
function SearchCtrl($rootScope,$scope,Signature) {
// console.log('SearchCtrl is invoked!!!!!!');
$scope.signature;
$scope.searcherrormsg='';
$scope.searchaction = function(barcodenum,signature) {
signature = Signature.query({rewardcardId:barcodenum});
$scope.signature = signature;
alert("data is " + $scope.signature.name); <=== This is UNDEFINED
};
}
apps.js file
angular.module('demo', ['demo.filters', 'demo.directives','demo.services.signature']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/search', {templateUrl: 'partials/search.html', controller: SearchCtrl});
$routeProvider.otherwise({redirectTo: '/search'});
service.js file
angular.module('demo.services.signature', ['ngResource']).
factory('Signature', function($resource){
return $resource('api/signature/:rewardcardId', {}, {
query: {method:'GET', params:{rewardcardId:'signature'}, isArray:false}
});
});
This is invoking database and server console is showing the following message ;
com.sun.jersey.api.container.filter.LoggingFilter$Adapter finish
INFO: 1 * Server out-bound response
1 < 200
1 < Content-Type: application/json
1 <
{"name":"xxx xxxx","customerid":187,"email":"xxxx#hotmail.com","sign":null,"barcode":"xxxx"}
And it displays return data at the HTML page properly. For example, the html page has
<p>{{signature.barcode}}
{{signature.name}}
which are displaying name and barcode properly as the above data set .
It only has an issue to get the data from the javascript that is saying undefined.
Whenever the javascript is trying to get the data from return resources from database, it is saying undefined.
You are trying to print the resource before it is available. The request to the server is asynchronous. Put alert("data is " + $scope.signature.name); in the success callback instead.
$scope.searchaction = function (barcodenum, signature) {
Signature.query({ rewardcardId: barcodenum },
function(data) {
$scope.signature = data;
alert("data is " + $scope.signature.name);
},
function(err) { // error handling can go here
});
};
I am not sure why you pass signature to $scope.searchaction and then perform an assignment operation on it.
[HttpPost]
public ActionResult accountchange(int id, int accountid, bool activate)
{
// Operations
return Json(new { Model = model, Result = true, Message = "Changed Successfully });
}
$('#accountchange-button').click(function () {
alert("");
$.post("url/accountchange/", {id:1, accountid:1, activate:1},
function (data) { $('.result').html(data); }, "json");
});
always got:
POST http://localhost/account/accountchange/ 500 (Internal Server Error)
f.support.ajax.f.ajaxTransport.sendjquery.min.js:4
f.extend.ajaxjquery.min.js:4
f.each.f.(anonymous function)jquery.min.js:4
(anonymous function)demo:105
f.event.dispatchjquery.min.js:3
f.event.add.h.handle.i
any idea?
In your code, I don't see model being defined. That's my best guess as to why your application is returning a 500 application error. As previously mentioned in the comment, you can use the inspect element utility to figure out what the server is actually complaining about.
[HttpPost]
public ActionResult accountchange(int id, int accountid, bool activate)
{
// Model = model is most likely undefined
return Json(new { Model = model, Result = true, Message = "Changed Successfully });
}
Have you set up your routing in Global.asax to accept the 3 parameters you are passing?
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}/{accountId}/{activate}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional, accountId = UrlParameter.Optional, activate = UrlParameter.Optional }
);