I'm trying to senda csv file opened with JS to the method written in C# where csv file will be parsed and added to database.
I have no problem with opening file and getting its contents.
But whatever I do with my Ajax call I receive empty data in the method CreateFromFile.
here you can see my code:
var a = fr.result;
$.ajax({
url: "/DeviceInstance/CreateFromFile",
type: "POST",
datatype: "html",
data: a,
error: function (data) {
alert("Dodanie nie powiodło się Jeden lub wiecej numerów seryjnych nie są nikalne " + data);
},
success: function (data) {
if (data.length > 0) {
alert(data);
}
else {
alert("Operacja zakonczona sukcesem")
}
}
});
and:
[HttpPost]
public JsonResult CreateFromFile(object data)
{
return Json("Sukces");
}
I'm asking how should i modify my code to make things work?
here : fr.result:
samsung;galaxy ;s3;1234567
samsung;galaxy ;s4;54321
samsung;galaxy ;s5;34567yu8
You could read the request input stream to access the body payload:
[HttpPost]
public JsonResult CreateFromFile()
{
byte[] data = new byte[Request.InputStream.Length];
Request.InputStream.Read(data, 0, data.Length);
string csv = Encoding.UTF8.GetString(data);
// ... do something with the csv
return Json("Sukces");
}
Also in your AJAX request you seem to have specified datatype: "html". There are 2 problems with this:
The parameter is called dataType instead of datatype.
You specified html but your controller action returns JSON.
So that's very inconsistent thing. I would recommend you to get rid of this parameter and leave jQuery use the response Content-Type header to automatically infer the correct type.
Try the following (assuming your a payload is really a string):
$.ajax({
url: '/DeviceInstance/CreateFromFile',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({ dane: a }),
/* callbacks */
});
And your controller action should now look like the following:
[HttpPost]
public JsonResult CreateFromFile(string dane)
{
// Parse CSV data from "dane"
}
Hope this helps.
Related
I am trying to get value based on 2 parameters, below is my function where I added my 2 parameters in JSON stringify :
function GetItemLocationOnHand(itemId, locationId) {
var data = JSON.stringify({
itemId: itemId,
locationId: locationId
});
$.ajax({
async: true,
type: 'GET',
dataType: 'JSON',
contentType: 'application/json; charset=utf-8',
data: data,
url: 'getItemInventory3',
success: function (data) {
$("#txtInventory3").val(parseFloat(data).toFixed(2));
},
error: function () {
alert("Error")
}
});
}
Below is my code in my controller to retrieve the data I want based on these two parameters :
[HttpGet]
public JsonResult GetItemLocationOnHand(int itemId, int locationId)
{
var itemLocQuantity = objDB.ItemLocationDatas.Single(items => items.ItemId == itemId && items.LocationId == locationId).Quantity;
return Json(itemLocQuantity, JsonRequestBehavior.AllowGet);
}
Upon calling this function via below on change code, I can't seem to get my data and is always returning the error.. If I only have 1 parameter, then no error encountered.
Please advise what went wrong when trying to pass 2 parameters.
$("#LocationId").change(function () {
var itemId = $("#ItemId").val();
var locationId = $("#LocationId").val();
GetItemLocationOnHand(itemId, locationId)
});
Issue solved by doing the following :
added correct URL which is GetItemLocationOnHand
removed Stringify and used var data = ({ itemId: itemId, locationId:
locationId });
thanks a lot to Freedom and Reflective and others for your comments!
function GetItemLocationOnHand(itemId, locationId) {
var data = ({ itemId: itemId, locationId: locationId });
$.ajax({
async: true,
type: 'GET',
dataType: 'JSON',
contentType: 'application/json; charset=utf-8',
data: data,
url: 'getItemLocationOnHand',
success: function (data) {
$("#txtInventory3").val(parseFloat(data).toFixed(2));
},
error: function () {
alert("Error")
}
});
}
Just to avoid some misunderstanding how AJAX GET works and setting some parameters which you don't have to set (i.e. you are still not so deep into jQuery AJAX) you may use the shortcut they also implemented i.e. $.get so your request will look as simple as that and you can't get wrong as it will use the proper defaults for GET. If you want the response to be treated as JSON, just set Content-type of your response headers (from backed) to application/json. This will be checked by jQuery AJAX response handler and it will parse the incoming data as JSON.
var data = {itemId: 1, locationId: 2 };
$.get('GetItemLocationOnHand', data, function (data) {
$("#txtInventory3").val(parseFloat(data).toFixed(2));
}).fail(function (jqXHR, textStatus ) {
alert(`Error = ${jqXHR.status} ${textStatus}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
See my example below. This works for me when doing ajax requests to a MVC controller with multiple params.
Below is my MVC controller action with multiple params.
// GET
[HttpGet]
public ActionResult Index(string referenceID, int typeID, int supplierID, bool isArchived)
{
// Do CODE here
}
Below is my Ajax request that I use to get or post. Depending on your needs. I use data type 'JSON' and format my data as a JSON object.
var formData = {referenceID: 'Test', typeID: 3, supplierID: 2, isArchived: false};
$.ajax({
type: 'GET',
cache: false,
url: getActionUrl, // url: domain/controller/action |or| domain/area/controller/action
dataType: 'json',
contentType: 'application/json; charset=utf-8',
headers: headers, // ignore if not needed. I use it for __RequestVerificationToken
data: formData,
success: function (data, status, xml) {
// do something with the data
},
error: function (xml, status, error) {
console.log(xml)
// do something if there was an error
},
complete: function (xml, status) {
}
});
I think your issue might be that you are using 'JSON.stringify'. It could be interpreting your JSON string as a single parameter input and not two separate parameters.
Please see below snippets from documentation. https://api.jquery.com/jquery.ajax/
If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.
The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. This processing can be circumvented by setting processData to false. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.
In a Post method within a Controller derived from ApiController what should I return to indicate success to jQuery ?
I've tried HttpResponseMessage but jQuery sees this as an error (even though the argument the jQuery error handler clearly has a 200 status).
The jQuery looks like this :
processParticipantEvent: function(parID, evtType, evtNotes, successFunction, errorFunction){
debugger;
var requestURL = '/api/participantevent';
var json = {"parId" : parID, "evtType": evtType, "evtNotes": evtNotes};
var jsonArray=JSON.stringify(json);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: jsonArray ,
dataType: "json",
success: function (data) { successFunction(data); },
error: function (data) { errorFunction(data); }
});
},
I've read this : Ajax request returns 200 OK, but an error event is fired instead of success which seems like it's touching on the same issue but I suspect it's out of data as it won't work for me ?
Just to be clear all I want to do is to return a plain old 2xx with no data.
As per the documentation:
"json": Evaluates the response as JSON and returns a JavaScript
object. Cross-domain "json" requests are converted to "jsonp" unless
the request includes jsonp: false in its request options. The JSON
data is parsed in a strict manner; any malformed JSON is rejected and
a parse error is thrown. As of jQuery 1.9, an empty response is also
rejected; the server should return a response of null or {} instead.
So if you want to use jQuery ajax you have to return a valid json string, just use the following in your API controller:
return Ok(new {});
Note this is a jQuery ajax "feature", using Angular for example to do an ajax post I can use return Ok(); inside my controller and everything works as expected.
As mentioned by #Beyers the return with OK() just works.
I've created the same structure here and worked.
My Controller has this:
[Route("api/participantevent")]
public IHttpActionResult Test()
{
return Ok("");
}
And at client I've changed your function just to simplify:
processParticipantEvent= function(){
debugger;
var requestURL = '/api/participantevent';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: [{'test': '1'}] ,
dataType: "json",
success: function (data) { alert('success'); },
error: function (data) { alert('error'); }
});
}
Your error is with the requestURL. Its value is absolute and http://api/participantevent does not exist. Try using a relative value.
var requestURL = './api/participantevent';
It seems that if you get an OK response, It is probably not a valid JSON.
I would recommend to you to check the HTTP response in the browser and try to run the JSON.parse function with the responseText and see whether it fails.
I usually declare a class like below:
public class AjaxResult
{
private bool success = true;
private List<string> messages;
public bool Success { get { return success; } set { success = value; } }
public List<string> Messages { get { return messages; } }
public AjaxResult()
{
messages = new List<string>();
}
}
In the controller, the action(to which the ajax request is made) should have JsonResult as return type.
[HttpPost]
public JsonResult Action(string id)
{
AjaxResult result = new AjaxResult();
//Set the properties of result here...
result.Success = true;
result.messages.Add("Success");
return Json(result);
}
3.And your ajax call will look like this:
$.ajax({
type: "POST",
dataType: 'json',
url: /ControllerName/Action,
data: { id: "Test"},
success: function (data) { alert('success'); },
error: function (data) { alert('error'); }
});
Ok. I've encountered a problem that i just can't understand.
First of all, i'm trying to post several ko.observableArrays to the controller as JSON and modelbinding them seperately. When i post only one and don't name it in the data attribute of .ajax it posts just fine and modelbinds flawlessly.
This is my a snippet from my viewModel and is how i am attempting to post the two JSON objects.
self.timeRanges = ko.observableArray();
self.geoRequirements = ko.observableArray();
self.saveWorkWish = function() {
$.ajax({
url: "#Url.Action("SaveWorkWish")",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: {
timeRanges: ko.toJSON(self.timeRanges()),
geoRequirements: ko.toJSON(self.geoRequirements())
},
complete: function (data) {
console.log(data);
}
});
};
My Action
public JsonResult SaveWorkWish(IList<JSONTimeRanges> timeRanges, IList<JSONGeoRequirements> geoRequirements)
{
// do stuff
}
I get this exception:
Invalid JSON primitive: timeRanges.
Interesting to note is that, when i do:
$.ajax({
url: "#Url.Action("SaveWorkWish")",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(self.timeRanges()),
complete: function (data) {
console.log(data);
}
});
And
public JsonResult SaveWorkWish(IList<JSONTimeRanges> timeRanges)
{
// do stuff
}
It works just fine.
Lastly a thing that i noticed, and is likely the cause of the error is that:
When i post 2 Jsons like in the example,
this is what chrome tells me i post:
timeRanges=%5B%7B%22startDate%22%3A%2214-09-2014%22%2C%22endDate%22%3A%2220-09-2014%22%2C.....etc..
and in the working example:
it is a well formated and readable JSON object.
So it seems like the error is indeed correct and that i am not sending valid JSON to the controller.
But..what am i doing wrong?
Try to convert observables to JSON first and then convert the whole object to json string:
data: JSON.stringify({
timeRanges: ko.toJS(self.timeRanges()),
geoRequirements: ko.toJS(self.geoRequirements())
}),
I am using html2canvs.js for taking screen shots of the page which is described here:
How to take screen shot of current webpage using javascript/jquery
The above process works fine, but now I want to pass the Base64 data to a c# method via ajax. My code looks like:
$('#gbox_Basic').html2canvas({
onrendered: function (canvas) {
var imgString = canvas.toDataURL("image/png");
$.ajax({
type: "POST",
url: "/Home/SentEmail2",
data: //how to pass base64 data 'imgString' ,
contentType: "multipart/form-data",
success: function () {
}
});
}
});
And here is my c# method
public void SentEmail2(what type of param it would accept?) {
//process incoming params
}
Give a try to this:
Controller.cs
[HttpPost]
public ActionResult Index(HttpPostedFileBase file) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
Form
The object FormData will hold the file element to be send.
var formData = new FormData($('form')[0]);
$.ajax({
url: '/Home/SentEmail2', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: beforeSendHandler,
success: completeHandler,
error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
References:
http://www.dustinhorne.com/post/2011/11/16/AJAX-File-Uploads-with-jQuery-and-MVC-3
http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx/
I've seen how I can serialize to an object in JSON. How can I POST a string which returns a ViewResult?
$.ajax({
url: url,
dataType: 'html',
data: $(this).val(), //$(this) is an html textarea
type: 'POST',
success: function (data) {
$("#report").html(data);
},
error: function (data) {
$("#report").html('An Error occured. Invalid characters include \'<\'. Error: ' + data);
}
});
MVC
[HttpPost]
public ActionResult SomeReport(string input)
{
var model = new ReportBL();
var report = model.Process(input);
return View(report);
}
How about:
$.ajax({
url: url,
dataType: 'html',
data: {input: $(this).val()}, //$(this) is an html textarea
type: 'POST',
success: function (data) {
$("#report").html(data);
},
error: function (data) {
$("#report").html('An Error occured. Invalid characters include \'<\'. Error: ' + data);
}
});
If you make the data a JSON object with a key that matches the parameter name MVC should pick it up.
On the MVC side...
[HttpPost]
public ActionResult SomeReport()
{
string input = Request["input"];
var model = new ReportBL();
var report = model.Process(input);
return View(report);
}
You might want to return your result as a json format. Not sure how to exactly do this with asp.net, but if it were Rails, it would be return #foo.to_json
You need to add a contentType. Look at the jQuery API:
http://api.jquery.com/jQuery.ajax/
You could use [FromBody] attribute in your action method, it specifies that a parameter or property should be bound using the request body.
[HttpPost]
public ActionResult SomeReport([FromBody] string input)
{
var model = new ReportBL();
var report = model.Process(input);
return View(report);
}