I am trying to build up a list of mock files for Dropzone.js to consume. I have an MVC controller method defined as follows:
[HttpPost]
public async Task<JsonResult> GetImageInfo(int imageId)
{
//int imgId;
//int.TryParse(imageId, out imgId);
var image = await RepublikDb.PropertyImage.FindAsync(imageId);
var path = Server.MapPath(image.ImageURI);
var size = new FileInfo(path).Length;
var fileName = new FileInfo(path).Name;
var thumbnailURI = image.ThumbnailImage.ImageURI.TrimStart('~');
return Json(new { fileName = fileName, size = size, thumbnailURI = thumbnailURI });
}
I have tested this endpoint with Postman, and everything works as expected, however each time I try and get the data in JS, the server returns a 500 error code, with complaints of the following: Exception Details: System.ArgumentException: The parameters dictionary contains a null entry for parameter 'imageId' of non-nullable type 'System.Int32'
Here is the JS AJAX code:
//Entry point to JS from razor. A comma separated string is passed here. Eg. imageIds = "10,12,14,16"
EditFormInit("#Model.PropertyImageIds")
var EditFormInit = function (imageIds) {
var imageIdsArr = imageIds.split(",");
var imageFiles = [];
imageIdsArr.forEach(function (ImageId) {
var requestData = { imageId: parseInt(ImageId) };
//var reqUrl = "?imageId=";
//reqUrl = reqUrl.concat(requestData.imageId.toString());
$.ajax({
type: "POST",
url: "/Admin/PropertyImage/GetImageInfo",
data: requestData,
contentType: "text/json; charset=utf-8",
dataType: "json",
success: function (data, status, jqXHR) {
var image = { fileName: data.fileName, size: data.size, thumbnail: data.thumbnailURI }
imageFiles.push(image);
}
});
});
Try:
contentType: "application/json"
This should work
so i finally realised why the controller was not getting hit, and resolved that issue. The $.ajax was passing the controller a JSON request, which was obviously failing.Once I removed the offending lines, the controller breakpoint finally got hit.
$.ajax({
type: "POST",
url: "/Admin/PropertyImage/GetImageInfo",
data: requestData,
success: function (data, status, jqXHR) {
var image = { fileName: data.fileName, size: data.size, thumbnail: data.thumbnailURI }
imageFiles.push(image);
}}
);
Even though the response from the controller is now coming back, the imageFiles array is still null. What am I doing wrong here?
Related
I am trying ajax Javascript Map, to spring controller. but it's getting null in backend. Please excuse if i am repeating question.
I can't change Map type, as my whole front end logic on it. Because set, get and has method from Map is what I need.
var ansMap = new Map(); // This way i created object
// added many values in ansMap,
$.ajax({
type: "POST",
url: myUrl,
contentType : 'application/json',
//cache: false,
dataType : 'json',
data : ansMap, // can't JSON.stringy(ansMap) as it gives empty json
success: function(result) {
console.log(result);
},
Spring code
#RequestMapping (value="myUrl", method=RequestMethod.POST)
public #ResponseBody String saveData(#RequestParam(required = false, value = "mapData") Map<String,List<String>> mapData, Model map)
{
log.info("Call Success");
log.info("mapData: "+mapData);
Please suggest what needs to be done here.
You can actually send your Map without mutating the value
var ansMap = new Map(); // This way i created object
// added many values in ansMap,
$.ajax({
type: "POST",
url: myUrl,
contentType : 'application/json',
//cache: false,
dataType : 'json',
data : JSON.stringify(Object.fromEntries(ansMap)), // can't JSON.stringy(ansMap) as it gives empty json
success: function(result) {
console.log(result);
},
That will turn it into a javascript object.
Object.fromEntries Will turn you Map into a javascript object, without altering the original Map
Regarding your backend i think you mis-interpret the #RequestParam annotation
The #RequestParam is to extract query parameters, form parameters and even files from the request.
I think that what you are looking for is #RequestBody.
Meaning you would be looking for something similar to :
#RequestMapping(value="/myUrl",method = RequestMethod.POST)
public String saveData( #RequestBody Map<String,Object> body) {
This should work
page
<button id="doPost"> post </button>
<script>
$(function () {
var map = new Map();
map.set('CIQ_2','aa');
map.set('CIQ_3','78965412300');
console.log(map);
$("#doPost").click (function() {
var settings = {
beforeSend: function(xhr, options) {
xhr.setRequestHeader("content-type" ,"application/json; charset=utf-8");
},
type: 'POST',
url: '/post' ,
data: JSON.stringify(Object.fromEntries(map))
}
$.ajax(settings).done(function(result) {
console.log("done : " + result);
});
});
});
</script>
Controller
#PostMapping("/post")
#ResponseBody
public String post(#RequestBody Map<String,String> data) {
System.out.println(data);
return "data well received";
}
will print
{CIQ_2=aa, CIQ_3=78965412300}
working code on GitHub
I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name
The JSON Object always return undefined in spite of the object contains data, i check it by using breakpoints in debugging
This is Action method in Controller:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
List<ComViewModel> comms = articleService.GetMoreComments(ArticleID, CommsCount);
return Json( comms );
}
and I also replaced the code in Action method to simple code like that but not work too:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
ComViewModel com = new ComViewModel
{
CommentContent = "cooooooooooontent",
CommentID = 99,
SpamCount = 22
};
return Json( com );
}
This is jQuery code for AJAX:
function GetMoreComments() {
$.ajax({
type: 'GET',
data: { CommsCount: #Model.Comments.Count, ArticleID: #Model.ArticleID },
url: '#Url.Action("GetMoreComments", "Comment")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var JsonParseData = JSON.parse(result);
alert(JsonParseData[0].CommentID)
alert(result[0].CommentID);
alert(result[0]["CommentID"]);
}
});
}
Usually you would have to parse your data if you need to alert it the way you have it. alert(result) should show data. If you need to access array of objects you must parse it first. Here is my example....
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
//PARSE data if you need to access objects
var resultstring = response.replace(',]',']');
var JsonParseData = JSON.parse(resultstring);
alert(JsonParseData[0].address)
});
That is wordpress ajax but its the same concept
I am trying to post a list of JSON objects to a controller, I have been trying to follow this post Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax However I get an error in the console saying that resource cannot be found even though the action is in the controller and I am passing it the right parameters and so the action method does not get hit on the breakpoint.
[HttpPost]
public ActionResult EditWidget(List<SaveWidgetModel> widget)
{
if (ModelState.IsValid)
{
foreach (var item in widget)
{
var targetWidget = db.widgets.Where(EditWidget => EditWidget.WidgetCode == item.id).FirstOrDefault();
targetWidget.x = item.x;
targetWidget.y = item.y;
targetWidget.height = item.height;
targetWidget.width = item.height;
db.Entry(targetWidget).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
return new EmptyResult();
}
and here is my javascript code
function SaveDashboard(){
var gridArray = _.map($('.grid-stack .grid-stack-item:visible'), function (el) {
el = $(el);
var gridID = el.find('.grid-stack-item-content.ui-draggable-handle').first().attr('id');
var node = el.data('_gridstack_node');
return {
id: gridID,
x: node.x,
y: node.y,
width: node.width,
height: node.height
};
});
gridArray = JSON.stringify({ 'widget' : gridArray});
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: 'Dashboard/EditWidgets/',
type: 'POST',
data: gridArray,
success: function (dataset) {
},
failure: function (xhr, error) {
console.log(xhr)
console.log(error)
},
});
}
Your controller action is singular
public ActionResult EditWidget()
but your AJAX call is plural
url: 'Dashboard/EditWidgets/
This maybe related to your url:
url: 'Dashboard/EditWidget/',
Maybe try
url: '/Dashboard/EditWidget/',
The forward slash tells it to start the search in the root, I think its looking for a folder at the top level
I am trying to get a pdf of a div in my view.
I am doing the following:
I get the element, uri encode its html, then pass it to a method via ajax:
AJAX:
function getPDF(html) {
$.ajax({
type: "POST",
url: "#Url.Action("printPage")",
data: { html: encodeURIComponent(html) }
}).done(function (result) {
window.open("data:application/pdf; " + result);
$("#printArea").html(result);
}).fail(function (data) {
alert("Failed");
});
}
Method:
[HttpPost]
public void printPage(string html)
{
String decoded = System.Uri.UnescapeDataString(html);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "something.pdf",
Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
var mem = Bcs.Common.Utilities.HTMLtoPDF.getPDF(decoded);
//var base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);
Response.BinaryWrite(mem.ToArray());
//return File(mem, System.Net.Mime.MediaTypeNames.Application.Octet);
}
In the end I get a popup to open a pdf but it won't open, according to adobe acrobat it is corrupt.
I tried sending the html as a perameter to the method, but the perameter is too long
HTTP Error 404.15 - Not Found The request filtering module is configured to deny a request where the query string is too long.
What would be a good way of doing this.
public JsonResult printPage(String html)
{
String decoded = System.Uri.UnescapeDataString(html);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "something.pdf",
Inline = false
};
var mem = Bcs.Common.Utilities.HTMLtoPDF.getPDF(decoded);
mem.Flush();
mem.Position = 0;
String b64Converted = Convert.ToBase64String(mem.ToArray());
return Json(b64Converted, JsonRequestBehavior.AllowGet );
System.Net.Mime.MediaTypeNames.Application.Octet);
}
Then in the view:
$.ajax({
type: "POST",
url: "#Url.Action("printPage")",
data: { html: encodeURIComponent(html) },
}).done(function (result) {
$("#printArea").append('PDF');
}).fail(function (data) {
alert("Failed");
});
Apparently its very easy
Just base64 the pdf and send it over at the json response.