abp.ajax({ Post Issue: Null Value being passed to the server side using abp.ajax({ - abp

I'm having some problems passing the data from my razor page to the server. It is passing NULL value from my abp.ajax({. Is there anything I'm missing from my ajax or the server-side code:
I'm using RAZOR PAGES ABP Framework 5.3
MY AJAX:
$("#frmDistrict").on("submit",
function (event) {
event.preventDefault();
const Url = $(this).attr("action");
const formData = $(this).serialize();
abp.ajax({
type: 'POST',
url: url,
data: JSON.stringify(formData)
}).then(function (result) {
if (data.isValid) {
if (data.IsNew) {
abp.notify.success(data.retmsg);
window.location.href = data.returl;
} else {
}
abp.notify.success(data.retmsg);
} else {
DisplayModelStateErrors(data.retmsg);
}
}).catch(function () {
alert("request failed :(");
});
});
MY SERVER CODE:
public async Task<JsonResult> OnPostAsync()
{
var rt = await Mediator.Send(new CreateDistrictCommand
{
District = district
});
if (rt.Failed) return new JsonResult(new { isValid = false, IsNew = true, retmsg =
rt.Message, sdata = rt.Data });
var retmsg = "District " + rt.Data.Name + " Created successfully.";
var returl = "/Districts/";
return new JsonResult(new { isValid = true, IsNew = true, retmsg, returl });
}
MY FORM
<form method="post" id="frmDistrict" >
<partial name="_AddEditDistrict" model="Model.District" />
</form>
If I use the standard ajax call
``$.ajax({ it works fine
but abp.ajax({ doesn't work
Many thanks
Zak

Related

Nativescript Class constructor Observable cannot be invoked without 'new'

I'm trying to upload a multipart form in nativescript and I'm using http-background. I keep getting the error Class constructor Observable cannot be invoked without 'new'. I've tried changing the compilerOptions target to es5 and es2017, but nothing changed.
Here's all my code from the component.
onSave(){
console.log("clicked")
this.proccessImageUpload(this.file);
}
public onSelectSingleTap() {
this.isSingleMode = true;
let context = imagepicker.create({
mode: "single"
});
this.startSelection(context);
}
private startSelection(context) {
let that = this;
context
.authorize()
.then(() => {
that.imageAssets = [];
that.imageSrc = null;
return context.present();
})
.then((selection) => {
console.log("Selection done: " + JSON.stringify(selection));
this.file = selection[0]._android;
that.imageSrc = that.isSingleMode && selection.length > 0 ? selection[0] : null;
// set the images to be loaded from the assets with optimal sizes (optimize memory usage)
selection.forEach(function (element) {
element.options.width = that.isSingleMode ? that.previewSize : that.thumbSize;
element.options.height = that.isSingleMode ? that.previewSize : that.thumbSize;
});
that.imageAssets = selection;
}).catch(function (e) {
console.log(e);
});
}
// proccess image function
proccessImageUpload(fileUri) {
var backgroundHttp = require("nativescript-background-http");
return new Promise((resolve, reject) => {
// body...
var request = {
url: 'http://192.168.0.2:4000/api/posts',
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"user_id": "<user_id>"
},
description: 'Uploading profile image..',
androidAutoDeleteAfterUpload: false,
androidNotificationTitle: 'Profile image'
}
var params = [
{ name: "title", value: "test" },
{ name: "content", value: "test" },
{ name: "fileToUpload", filename: fileUri, mimeType: "image/jpeg" }
];
var backgroundSession = backgroundHttp.session('image-upload');
var task = backgroundSession.uploadFile(fileUri, request);
task.on("progress", (e) => {
// console log data
console.log(`uploading... ${e.currentBytes} / ${e.totalBytes}`);
});
task.on("error", (e) => {
// console log data
console.log(`Error processing upload ${e.responseCode} code.`);
reject(`Error uploading image!`);
});
task.on("responded", (e) => {
// console log data
console.log(`received ${e.responseCode} code. Server sent: ${e.data}`);
// var uploaded_response = JSON.parse(e.data);
});
task.on("complete", (e) => {
// console log data
console.log(`upload complete!`);
console.log(`received ${e.responseCode} code`);
// console.log(e.data);
})
resolve(task);
});
}
I know the issue is coming from this line.
var task = backgroundSession.uploadFile(fileUri, request);
Any help would be greatly appreciated!
You use old version if nativescript-background-http plugin
You have to install latest version
tns plugin add #nativescript/background-http
I was able to get this working by installing tns version 6.
I had exactly the same problem. I got this from slack.com, compliments Chris Vietor
"tns plugin add nativescript-background-http" works with nativescript 6.
"tns plugin add #nativescript/background-http" works with nativescript 7.

Passing params: to Web API works with $http.get but not $http.Post

AngularJS 1.59
This API call works with $http.get.
JS ViewModel
$scope.placeOrder = function () { //'api/order/create'
var order = { AccountId : accountId, Amount : $scope.subTotal,
Tax: $scope.tax, Shipping: $scope.shipping }
var orderJSON = JSON.stringify(order);
viewModelHelper.apiGet('api/order/create', { params: { order: orderJSON } },
function (result) {
var orderId = result.data;
});
}
App.js
self.apiGet = function (uri, data, success, failure, always) {
self.isLoading = true;
self.modelIsValid = true;
$http.get(AlbumApp.rootPath + uri, data)
.then(function (result) {
success(result);
if (always != null)
always();
self.isLoading = false;
}, function (result) {
if (failure == null) {
if (result.status != 400)
self.modelErrors = [result.status + ': ' + result.statusText +
' - ' + result.data];
else
self.modelErrors = [result.data + ''];
self.modelIsValid = false;
}
else
failure(result);
if (always != null)
always();
self.isLoading = false;
});
}
self.apiPost = function (uri, data, success, failure, always) {
self.isLoading = true;
self.modelIsValid = true;
$http.post(AlbumApp.rootPath + uri, data)
.then(function (result) {
success(result);
if (always != null)
always();
self.isLoading = false;
}, function (result) {
if (failure == null) {
if (result.status != 400)
self.modelErrors = [result.status + ': ' + result.statusText + ' - ' + result.data];
else self.modelErrors = [result.data];
self.modelIsValid = false;
}
else failure(result);
if (always != null) always();
self.isLoading = false;
});
}
APIController
[HttpGet]
[Route("create")]
public IHttpActionResult Create(string order) {
var _order = JsonConvert.DeserializeObject<Order>(order); ... }
But since this is a Create function I want to use $http.post. When I change the call to
$scope.placeOrder = function () { //'api/order/create'
var order = { AccountId : accountId, Amount : $scope.subTotal,
Tax: $scope.tax, Shipping: $scope.shipping }
var orderJSON = JSON.stringify(order);
viewModelHelper.apiPost('api/order/create', { params: { order: orderJSON } },
//null,
function (result) {
var orderId = result.data;
});
}
and my controller Action to
[HttpPost]
[Route("create")]
public IHttpActionResult Create(string order) {
var _order = JsonConvert.DeserializeObject<Order>(order); ... }
I get a 404 error:
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:50597/api/order/create'.
</Message>
<MessageDetail>
No action was found on the controller 'OrderApi' that matches the request.
</MessageDetail>
</Error>
Is this a bug or am I missing some conceptual point or do I have an error in my code?
Solution: (Thank you Giovani)
params: needs to be passed to the config in the $http.get and $http.post. The two methods have different signatures.
In apiGet renamed data to config.
In apiPost added a config.
In apiPost call added a null so the params: is passed to config rather than data.
App.js
self.apiGet = function (uri, config, success, failure, always) {
self.isLoading = true;
self.modelIsValid = true;
$http.get(AlbumApp.rootPath + uri, config)
...
self.apiPost = function (uri, data, config, success, failure, always) {
self.isLoading = true;
self.modelIsValid = true;
$http.post(AlbumApp.rootPath + uri, data, config)
JS ViewModel
$scope.placeOrder = function () { //'api/order/create'
var order = { AccountId : accountId, Amount : $scope.subTotal,
Tax: $scope.tax, Shipping: $scope.shipping }
var orderJSON = JSON.stringify(order);
viewModelHelper.apiPost('api/order/create', null, { params: { order: orderJSON } },
function (result) {
var orderId = result.data;
}); }
$http.get() and $http.post() have a different method signature. more info
$http.get(<URL>, <DATA (params, responseType, etc..)>)
$http.post(<URL>, <BODY_DATA>, <DATA (params, responseType, etc..)>

Inserting new record from AngularJS using Web API

Hi I'm a newbie in web development and I'm having some trouble in inserting new data in my database.
First, there's an error in dbcontext.Tbl_Articles.Add(adto);
It says, cannot convert WebAPI.Models.Articles to WebAPI.DataLayer.Tbl_Articles
Another thing is, whenever I run my Web API, it says something like this - {"Message":"The requested resource does not support http method 'GET'."}
script file:
$scope.AddArticle = function ()
{
var data =
{
Category: $scope.Category,
IsCarousel: $scope.IsCarousel,
IsImportant: $scope.IsImportant,
HeaderImage: $scope.HeaderImage,
Title: $scope.Title,
ByLine: $scope.ByLine,
Content: $scope.Content,
Author: $scope.Author,
PublishStartDate: $scope.PublishStartDate_date + " " + $scope.PublishStartDate_time + $scope.PublishStartDate_time_ext,
PublishEndDate: $scope.PublishEndDate_date + " " + $scope.PublishEndDate_time + $scope.PublishEndDate_time_ext
};
$http(
{
method: 'POST',
url: 'http://project-aphrodite-uat-service.azurewebsites.net/api/articles/createarticle',
data: JSON.stringify(data)
})
.then(function successCallback(response)
{
console.log(response);
},
function errorCallback(response)
{
console.log("error" + response);
});
};
ArticlesController.cs:
[HttpPost]
[Route("api/articles/createarticle")]
public Articles CreateArticle(Articles obj)
{
DataLayer.DataLayer dl = new DataLayer.DataLayer();
dl.CreateArticle(obj);
return obj;
}
DataLayer.cs:
public string CreateArticle(Articles obj)
{
var adto = new Articles();
adto.Category = obj.Category;
adto.IsCarousel = obj.IsCarousel;
adto.IsImportant = obj.IsImportant;
adto.HeaderImage = obj.HeaderImage;
adto.Title = obj.Title;
adto.ByLine = obj.ByLine;
adto.Content = obj.Content;
adto.Author = obj.Author;
adto.PublishStartDate = obj.PublishStartDate;
adto.PublishEndDate = obj.PublishEndDate;
using (ArticleEntities dbcontext = new ArticleEntities())
{
dbcontext.Tbl_Articles.Add(adto);
dbcontext.SaveChanges();
return "test";
}
}
I hope someone could help me fix these. Thankie so much!

How to download files using axios.post from webapi

I have a complex object parameter that I need to send as post, as it could be too long for querystring. The post call is asking to have an excel file dynamically generated and then downloaded asynchronously. But all of this is happening inside of a react application. How does one do this using axios.post, react, and webapi? I have confirmed that the file does generate and the download up to the response does come back, but I'm not sure how to actually open the file. I have a hidden iframe that I'm trying to set the path, src, of the file to, but I dont know what response property to use.
// webapi
[HttpPost]
public HttpResponseMessage Post([FromBody]ExcelExportModel pModel)
{
var lFile = ProductDataModel.GetHoldingsExport(pModel);
var lResult = new HttpResponseMessage(HttpStatusCode.OK);
lResult.Content = new ByteArrayContent(lFile);
lResult.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "HoldingsGridExport.xls"
};
lResult.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return lResult;
}
// client side api
static getHoldingsExport({ UserConfigurationID, UserID, Configurations, ViewName, SortModel, FilterModel, UserConfigType, IsDefault, LastPortfolioSearchID = null, ProductId }) {
const filterModel = JSON.stringify(FilterModel); // saving as string as this model is dynamically generated by grid out of my control
const sortModel = JSON.stringify(SortModel);
let params = JSON.stringify({
UserConfigurationID,
UserID,
Configurations,
ViewName,
filterModel,
sortModel,
UserConfigType,
IsDefault,
LastPortfolioSearchID,
ProductId
});
return axiosInstance.post("/api/HoldingsExport", params);
}
// client side app call to get file
HoldingsApi.getHoldingsExport(config)
.then(function(response) {
debugger;
let test = response;
})
.catch(error => {
toastr.success('Failed to get export.');
});
This is how I've achieved file downloads by POSTing via Axios:
Axios.post("YOUR API URI", {
// include your additional POSTed data here
responseType: "blob"
}).then((response) => {
let blob = new Blob([response.data], { type: extractContentType(response) }),
downloadUrl = window.URL.createObjectURL(blob),
filename = "",
disposition = response.headers["content-disposition"];
if (disposition && disposition.indexOf("attachment") !== -1) {
let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/,
matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, "");
}
}
let a = document.createElement("a");
if (typeof a.download === "undefined") {
window.location.href = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
}).catch((error) => {
// ...
});
Just in case the above solution does not serve you quite well, here is how I could be able to download videos that are hosted on S3 AWS buckets,
const handleDownload = () => {
const link = document.createElement("a");
link.target = "_blank";
link.download = "YOUR_FILE_NAME"
axios
.get(url, {
responseType: "blob",
})
.then((res) => {
link.href = URL.createObjectURL(
new Blob([res.data], { type: "video/mp4" })
);
link.click();
});
};
And I trigger handleDownload function in a button with onClick.
The url in the function has the video URL from S3 buckets

implementing socket.io on existing application

My current application poll using MEAN stack and in controller I have a function vote() and API route defined as follow:
"/api/polls/pollID/pollChoiceID"
(ex. http://localhost:3001/api/polls/5587ad060a9e110816f9f1a8/5587ad060a9e110816f9f1a9)
I have the app working fine as it's but now I'm looking to implement socket.io on this app so that when client #2 connected and vote the voting result graph of client #1 will update in real time. I did some research about socket.io but I'm still stuck on implementing it.
For instance, in controller.js and inside the vote() I need to add:
socket.emit('send:vote', poll);
and over the routes/index.js I'll need to handle the socket.emit from controller so I wrap existing router.post codes with socket.on :
socket.on('send:vote', function(data){
router.post('/api/polls/:poll_id2/:poll_choice2', function(req, res)
{
//existing code here
}
}
However, Ii'm not sure if I'm taking the right steps so that they will work with my existing API route. Any inputs would be great! Thanks
/*
controller.js
*/
var voteObj = { poll_id1: pollSelected, choice1: pollChoiceSelected };
$scope.votedPollID = voteObj.poll_id1;
$scope.votedPollChoiceID = voteObj.choice1;
$scope.vote = function()
{
$http.post('/api/polls/' + $scope.votedPollID + '/' + $scope.votedPollChoiceID)
.success(function (data)
{
console.log(data);
$scope.poll = data;
})
.error(function(data) {
console.log('Error: ' + data);
})
/*
routes/index.js
*/
router.post('/api/polls/:poll_id2/:poll_choice2', function(req, res)
{
var testpollid = req.params.poll_id2;
var testpollchoiceid = req.params.poll_choice2;
var ipCounter = 0;
PollModel.findById({_id: req.params.poll_id2}, function(err, poll)
{
if(poll)
{
var choice = poll.choices.id(testpollchoiceid);
choice.votes.push({ ip: ip });
var ipCounter = ipCounter++;
poll.save(function(err, doc)
{
if(err)
{
return (err);
}
else
{
var theDoc = {
question: doc.question, id: doc._id, choices: doc.choices,
userVoted: false, totalVotes: 0
};
for(var i = 0, ln = doc.choices.length; i< ln; i++)
{
var choice = doc.choices[i];
for(var j= 0, jLn = choice.votes.length; j< jLn; j++)
{
var vote = choice.votes[j];
theDoc.totalVotes++;
theDoc.ip = ip;
if(vote.ip === ip)
{
theDoc.userVoted = true;
theDoc.userChoice = { _id: choice._id, text: choice.text };
}
}
}
poll.userVoted = theDoc.userVoted;
}
});
return res.json(poll);
}
else
{
return res.json({error:true});
}
});
});
});
});

Resources